Springboot整合shiro
添加依赖
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.7.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
编写shiro配置类
需要实现shiro中的三个核心对象:Subject、SecurityManager、Realm
@Configuration public class ShiroConfig { //ShiroFilterFactoryBean(过滤器工厂对象:初始化SecurityManager、请求处理) @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // 设置 securityManager shiroFilterFactoryBean.setSecurityManager(securityManager); LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); // 内置过滤器
//anon:无需认证
//authc:必须认证
//user:必须有记住我功能才能使用
//perms:指定权限
//role:指定角色 filterChainDefinitionMap.put("/**", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } //DefaultWebSecurityManager(对应SecurityManager对象) @Bean public SecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // 配置 SecurityManager,并注入 shiroRealm securityManager.setRealm(shiroRealm()); return securityManager; } //Realm 需要自定义 @Bean public ShiroRealm shiroRealm() { // 配置 Realm return new ShiroRealm(); } }
Realm
public class ShiroRealm extends AuthorizingRealm { /** * 认证 * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { return null; } /** * 授权 * @param principalCollection * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { return null; } }
Controller
@Controller public class IndexController { @GetMapping("/index") public String index(){ return "index"; } }
访问结果失败:认证失败,并且没有登录页面,