文章目录
依赖
<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version><mybatis.spring.boot.version>1.3.1</mybatis.spring.boot.version><druid.version>1.0.28</druid.version><shiro.version>1.3.2</shiro.version><kaptcha.version>0.0.9</kaptcha.version></properties><!-- 集成shiro版本 --><properties><shiro.version>1.3.2</shiro.version><kaptcha.version>0.0.9</kaptcha.version></properties><!-- spring集成shiro --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>${shiro.version}</version></dependency><!-- shiro缓存 --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-ehcache</artifactId><version>${shiro.version}</version></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>${mybatis.spring.boot.version}</version></dependency><!-- 集成验证码 --><dependency><groupId>com.github.axet</groupId><artifactId>kaptcha</artifactId><version>${kaptcha.version}</version></dependency>
Shiro 配置类
package com.qf.config;import com.qf.realm.UserRealm;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
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.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
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 ShiroConfig {//1,创建 SessionManager 管理会话@Bean(name = "sessionManager")//<bean class="">public SessionManager sessionManager(){DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();//设置过期时间sessionManager.setGlobalSessionTimeout(1000*60*30);//设置后台线程 清理过期的会话sessionManager.setSessionValidationSchedulerEnabled(true);//设置地址比拼接sessionidsessionManager.setSessionIdUrlRewritingEnabled(false);return sessionManager;}//2,创建SecurityManager@Bean(name="securityManager")public SecurityManager securityManager(SessionManager sessionManager,UserRealm userRealm){DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();securityManager.setSessionManager(sessionManager);//缓存管理EhCacheManager cacheManager = new EhCacheManager();cacheManager.setCacheManagerConfigFile("classpath:ehcache.xml");securityManager.setCacheManager(cacheManager);//cookie管理CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();Cookie cookie = cookieRememberMeManager.getCookie();cookie.setMaxAge(60*60*24*3);cookie.setPath("/");securityManager.setRememberMeManager(cookieRememberMeManager);//设置自定义realmsecurityManager.setRealm(userRealm);return securityManager;}//3,创建ShiroFilter@Bean(name="shiroFilter")public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();shiroFilterFactoryBean.setSecurityManager(securityManager);//设置登录页面shiroFilterFactoryBean.setLoginUrl("/login.html");shiroFilterFactoryBean.setSuccessUrl("/index.html");shiroFilterFactoryBean.setUnauthorizedUrl("unauthorized.html");//拦截的路径的详细设置//什么Map是存取有序的?Map<String,String> map = new LinkedHashMap<>();map.put("/sys/login","anon");//匿名访问map.put("/captcha.jpg","anon");//验证码放行map.put("/**","authc");shiroFilterFactoryBean.setFilterChainDefinitionMap(map);return shiroFilterFactoryBean;}//4,BeanLifeCycle 生命周期@Bean(name="lifecycleBeanPostProcessor")public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){LifecycleBeanPostProcessor lifecycleBeanPostProcessor = new LifecycleBeanPostProcessor();return lifecycleBeanPostProcessor;}//5,开启aop对shiro的bean动态代理@Bean(name = "defaultAdvisorAutoProxyCreator")public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);//cglib方式return defaultAdvisorAutoProxyCreator;}/*** 6.开启shiro的注解** @param securityManager* @return*/@Bean(name = "authorizationAttributeSourceAdvisor")public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();advisor.setSecurityManager(securityManager);return advisor;}
}
自定义Realm
package com.qf.realm;import com.qf.pojo.SysUser;
import com.qf.service.MenuService;
import com.qf.service.RoleService;
import com.qf.service.SysUserService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.util.List;@Component
public class UserRealm extends AuthorizingRealm {@Autowiredprivate SysUserService sysUserService;@Autowiredprivate RoleService roleService;@Autowiredprivate MenuService menuService;/*** 先认证** @param token* @return* @throws AuthenticationException*/@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {//1.得到用户名和密码UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;String username = usernamePasswordToken.getUsername();//默认获取password的类型为char[],转换处理String password = new String(usernamePasswordToken.getPassword());//2.从数据库根据用户名查询用户信息SysUser byUsername = sysUserService.findByUsername(username);//判断查询出的用户对象(sysUser)是否为空if(byUsername==null){throw new UnknownAccountException("账户不存在");}//判断查询出的用户对象的用户密码和页面从页面传递过来的密码进行比较是否相同if(!byUsername.getPassword().equals(password)){throw new IncorrectCredentialsException("密码不正确");}//判断查询出的用户对象的用户的可用状态 0 -> 账户冻结状态if(byUsername.getStatus()==0){throw new LockedAccountException("账户被冻结");}SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(byUsername,password,this.getName());return info;}/*** 后授权** @param principals* @return*/@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {//1.从principals中获取用户信息SysUser sysUser = (SysUser)principals.getPrimaryPrincipal();//2.获取userIdLong userId = sysUser.getUserId();//3.通过userId获取当前用户的角色信息List<String> rolsByUserID = roleService.findRolsByUserID(userId);//4.通过userId获取当前用户的权限信息List<String> permsByUserId = menuService.findPermsByUserId(userId);//5.把角色和权限信息封装到SimpleAuthorizationInfo中,进行返回SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();info.addRoles(rolsByUserID);info.addStringPermissions(permsByUserId);return info;}
}