使用场景:

  • 在web微服务中做登录控制,没登录时自动跳转到登录页面

  • 原理:
    使用filter对路由进行拦截过滤,然后再路由跳转,如果知道怎么搞的话,就不用往下看了,因为比较简单粗暴。

依旧是几步搞定

		<dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.2.2</version>
        </dependency>

如果你第一步搞完的话里面应该已经有了下面两个依赖,如果没有,回到第一步粗暴搞完

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  • 第三步 上配置
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

   @Bean
   public SecurityManager sercurityManager(){
      return new DefaultWebSecurityManager();
   }

   @Bean
   public ShiroFilterFactoryBean filterFactoryBean(SecurityManager securityManager){
      /**
       * 准备拦截器的拦截路径
       * 需要保持拦截顺序,所以用linkedHashMap,一般将/**放在最下面
       */
      Map<String, String> filterMap = new LinkedHashMap<>();
      filterMap.put("/logout", "logout");
      //authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问
      filterMap.put("/**", "authc");

      ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
      shiroFilterFactoryBean.setSecurityManager(securityManager);
      //需要登录的页面
      shiroFilterFactoryBean.setLoginUrl("/login");
      //登录成功的页面
      shiroFilterFactoryBean.setSuccessUrl("/index");
      shiroFilterFactoryBean.setUnauthorizedUrl("/error");
      shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
      return shiroFilterFactoryBean;
   }


}
  • 开始测试
    启动服务,访问 http://localhost:8001 就自动跳转到了 http://localhost:8001/login
    在这里插入图片描述
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐