Springboot shiro (一)拦截路由,自动跳转到登录页面
使用场景:在web微服务中做登录控制,没登录时自动跳转到登录页面原理:使用filter对路由进行拦截过滤,然后再分发跳转,如果知道怎么搞得话,就不用往下看了,因为比较简单粗暴。依旧是几步搞定第一步准备微服务springboot中使用thymeleaf访问页面参照上面链接粗暴的搞完,直到可以访问到页面第二步 上依赖<dependency>...
·
使用场景:
-
在web微服务中做登录控制,没登录时自动跳转到登录页面
-
原理:
使用filter对路由进行拦截过滤,然后再路由跳转,如果知道怎么搞的话,就不用往下看了,因为比较简单粗暴。
依旧是几步搞定
- 第一步 准备微服务
springboot中使用thymeleaf访问页面
参照上面链接粗暴的搞完,直到可以访问到页面 - 第二步 上依赖
<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
更多推荐
已为社区贡献4条内容
所有评论(0)