🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## springboot + shiro +redis ## 引入外部资源(maven) ``` <!-- shiro-spring --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.1</version> </dependency> <!-- shiro-core --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.4.1</version> </dependency> <!-- shiro-redis --> <dependency> <groupId>org.crazycake</groupId> <artifactId>shiro-redis</artifactId> <version>3.2.3</version> </dependency> ``` ## 创建ShiroConfiguration.java (Shiro配置的主体) ``` import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.servlet.SimpleCookie; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.crazycake.shiro.RedisCacheManager; import org.crazycake.shiro.RedisManager; import org.crazycake.shiro.RedisSessionDAO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.LinkedHashMap; import java.util.Map; @Configuration public class ShiroConfiguration { private final static Logger logger = LoggerFactory.getLogger(ShiroConfiguration.class); // 下面两个方法对 注解权限起作用有很大的关系,请把这两个方法,放在配置的最上面 @Bean(name = "lifecycleBeanPostProcessor") public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } @Bean public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator(); autoProxyCreator.setProxyTargetClass(true); return autoProxyCreator; } //将自己的验证方式加入容器 @Bean public UserRealm myRealm() { UserRealm myRealm = new UserRealm(); return myRealm; } // 配置sessionDAO @Bean(name = "redisSessionDAO") public RedisSessionDAO getRedisSessionDAO(){ RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); redisSessionDAO.setRedisManager(redisManager()); return redisSessionDAO; } //配置shiro session 的一个管理器 @Bean(name = "sessionManager") public DefaultWebSessionManager getDefaultWebSessionManager(){ DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setSessionDAO(getRedisSessionDAO()); // 设置session过期时间 sessionManager.setGlobalSessionTimeout(3600000L); //删除过期的session sessionManager.setDeleteInvalidSessions(true); //定期检查失效的session sessionManager.setSessionValidationSchedulerEnabled(true); //设置检查的间隔时间 sessionManager.setSessionValidationInterval(10000); //所有的sessionid存入到cookie中 sessionManager.setSessionIdCookie(simpleCookie()); //定义sessionid 的cookie模板可以进行操作 sessionManager.setSessionIdCookieEnabled(true); return sessionManager; } //cacheManaganer @Bean("cacheManager") public RedisCacheManager redisCacheManager(){ RedisCacheManager redisCacheManager = new RedisCacheManager(); redisCacheManager.setRedisManager(redisManager()); return redisCacheManager; } /** * cookie模板 * @return */ @Bean(name = "simpleCookie") public SimpleCookie simpleCookie(){ SimpleCookie simpleCookie = new SimpleCookie("daf.session.session.id");☆1 simpleCookie.setPath("/"); simpleCookie.setHttpOnly(true); simpleCookie.setMaxAge(-1); return simpleCookie; } @Bean(name = "securityManager") public DefaultWebSecurityManager getDefaultWebSecurityManager() { DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(); defaultWebSecurityManager.setRealm( myRealm() ); // 将sessionDAO放进来 defaultWebSecurityManager.setSessionManager( getDefaultWebSessionManager() ); return defaultWebSecurityManager; } @Bean public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor( DefaultWebSecurityManager securityManager) { AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); advisor.setSecurityManager(securityManager); return advisor; } //Filter工厂,设置对应的过滤条件和跳转条件 @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(org.apache.shiro.mgt.SecurityManager securityManager ) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); //拦截器. Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>(); // 配置不会被拦截的链接 顺序判断 filterChainDefinitionMap.put("/static/**", "anon"); filterChainDefinitionMap.put("/assets/**", "anon"); filterChainDefinitionMap.put("/page/**", "anon"); filterChainDefinitionMap.put("/register.html", "anon"); filterChainDefinitionMap.put("/register", "anon"); filterChainDefinitionMap.put("/login.html", "anon"); filterChainDefinitionMap.put("/checkPhone", "anon"); filterChainDefinitionMap.put("/sendCode", "anon"); filterChainDefinitionMap.put("/login", "anon"); //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了 filterChainDefinitionMap.put("/logout", "logout"); //<!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了; //<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问--> filterChainDefinitionMap.put("/**", "authc"); // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面 shiroFilterFactoryBean.setLoginUrl("/login.html"); // 登录成功后要跳转的链接 shiroFilterFactoryBean.setSuccessUrl("http://127.0.0.1:8082"); //未授权界面; shiroFilterFactoryBean.setUnauthorizedUrl("/403.html"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } /** * redis session 管理器 * @return */ @Bean(name = "redisManager") public RedisManager redisManager(){ RedisManager redisManager= new RedisManager(); redisManager.setHost("127.0.0.1:6379"); redisManager.setDatabase(0); return redisManager; } } ``` 如果是有子域名的项目可以在simpleCookie方法中添加: ``` simpleCookie.setDomain(".xxxx.com"); ``` **☆1:构造内可以自定义cookie名称** ## 创建Realm进行登陆验证和权限认证(主体配置中的myRealm方法) ``` import com.vshu.entity.pojo.auth.User; import com.google.common.collect.Maps; import com.vshu.service.auth.user.UserService; import org.apache.dubbo.config.annotation.Reference; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import java.util.Map; public class UserRealm extends AuthorizingRealm { @Autowired private UserService userService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { User user = (User) SecurityUtils.getSubject().getPrincipal(); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { String username = (String) authenticationToken.getPrincipal(); Map<String,String> map = Maps.newConcurrentMap(); map.put("phone",username); User user = userService.findByUserPhone(map); if (user == null) { throw new UnknownAccountException(); // 账号不存在 } if (user.getEnable() == 0) { throw new LockedAccountException(); // 账号被锁定 } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getPhone()), getName()); return authenticationInfo; } } ``` ##配置完成