导入依赖
<!--thymeleaf集成shiro模版-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.4.0</version>
</dependency>
springboot配置类
在springboot项目中配置shiro,包括密码加盐处理、记住密码、自动登录session管理等Bean以及自定义过滤器的配置。
/**
* Description: shiro相关配置
*
*/
@Configuration
public class ShiroConf {
/**
* shiro session的管理
*/
@Bean
public DefaultWebSessionManager sessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
// 会话超时时间,单位:毫秒,默认30分钟(1800000)
sessionManager.setGlobalSessionTimeout(1800000);
// 定时清理失效会话, 清理用户直接关闭浏览器造成的孤立会话
sessionManager.setSessionValidationInterval(1800000);
sessionManager.setSessionValidationSchedulerEnabled(true);
// 指定sessionid
sessionManager.setSessionIdCookie(sessionIdCookie());
sessionManager.setSessionIdCookieEnabled(true);
sessionManager.getSessionIdCookie().setSecure(false);
// 去掉shiro登录时url里的JSESSIONID
sessionManager.setSessionIdUrlRewritingEnabled(false);
return sessionManager;
}
/**
* cookie对象;
* rememberMeCookie()方法是设置Cookie的生成模版,比如cookie的name,cookie的有效时间等等。
*/
@Bean
public SimpleCookie rememberMeCookie(){
//这个参数是cookie的名称,对应前端的name = rememberMe
SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
//<!-- 记住我cookie生效时间 ,单位秒;-->
simpleCookie.setMaxAge(Cookie.ONE_YEAR);
return simpleCookie;
}
/**
* cookie管理对象;
* rememberMeManager()方法是生成rememberMe管理器,而且要将这个rememberMe管理器设置到securityManager中
*/
@Bean
public CookieRememberMeManager rememberMeManager(){
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
//rememberMe cookie加密的密钥 默认AES算法 密钥长度(128 256 512 位)
cookieRememberMeManager.setCipherKey("x5+126q47832#4*k".getBytes());
return cookieRememberMeManager;
}
/**
* 防止放行的静态资源等请求修改存sessionid的cookie
*/
@Bean
public SimpleCookie sessionIdCookie() {
SimpleCookie sessionIdCookie = new SimpleCookie("sid");
sessionIdCookie.setHttpOnly(true);
sessionIdCookie.setMaxAge(-1);
return sessionIdCookie;
}
/**
* shiro 加密登录 密码加盐处理
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
// 散列算法
hashedCredentialsMatcher.setHashAlgorithmName(EncryptUtil.ALGORITHM_NAME);
// 散列次数
hashedCredentialsMatcher.setHashIterations(EncryptUtil.HASH_ITERATIONS);
return hashedCredentialsMatcher;
}
/**
* shiro realm
*
* @return 自定义loginRealm
*/
@Bean
public Realm loginRealm() {
LoginRealm loginRealm = new LoginRealm();
loginRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return loginRealm;
}
/**
* 安全管理器
*
* @return DefaultWebSecurityManager
*/
@Bean
public DefaultWebSecurityManager securityManager() {
DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
webSecurityManager.setCacheManager(new MemoryConstrainedCacheManager());
// 自定义session管理
webSecurityManager.setSessionManager(sessionManager());
//注入记住我管理器
webSecurityManager.setRememberMeManager(rememberMeManager());
webSecurityManager.setRealm(loginRealm());
return webSecurityManager;
}
/**
* 为了在thymeleaf里使用shiro的标签的bean
*/
@Bean
public ShiroDialect shiroDialect() {
return new ShiroDialect();
}
/**
* 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions)
* 配置以下两个bean(DefaultAdvisorAutoProxyCreator和AuthorizationAttributeSourceAdvisor)即可实现此功能
*
* @return DefaultAdvisorAutoProxyCreator
*/
@Bean
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
/**
* 开启shiro注解
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
return authorizationAttributeSourceAdvisor;
}
/**
* ShiroFilterFactoryBean 使用自定义过滤器并定义过滤规则和优先级顺序,loginFilter为自定义过滤器,user为shiro框架中的过滤器,当前用于记住密码自动登录功能
*
* @return ShiroFilterFactoryBean
*/
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean() {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
bean.setSecurityManager(securityManager());
bean.setFilterChainDefinitions(
"/css/** = anon\n" +
"/images/** = anon\n" +
"/webjars/** = anon\n" +
"/img/** = anon\n" +
"/js/** = anon\n" +
"/fonts/** = anon\n" +
"/error = anon\n" +
"/** = loginFilter,user");
bean.setSuccessUrl("/");
bean.setLoginUrl("/login");
HashMap<String, Filter> filters = new HashMap<>();
filters.put("loginFilter", new LoginFilter());
bean.setFilters(filters);
return bean;
}
}
自定义Realm实现认证和授权
public class LoginRealm extends AuthorizingRealm {
@Autowired
IUserService userServiceImpl;
/**
* Description: 授权
*
* @param principals principals
* @return AuthorizationInfo
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
UserInfo userInfo = (UserInfo) getAvailablePrincipal(principals);
SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
// 授权用户
for (RoleInfo role : userInfo.getRoles()) {
authorizationInfo.addRole(role.getRole());
for (PermissionInfo permission : role.getPermissions()) {
authorizationInfo.addStringPermission(permission.getName());
}
}
return simpleAuthorInfo;
}
/**
* Description: 验证
*
* @param token AuthenticationToken
* @return AuthenticationInfo
* @throws AuthenticationException AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UserToken userToken = (UserToken) token;
// 根据用户名查询用户信息
UserInfo user = userServiceImpl.findByLoginName(userToken.getUserName());
if (user == null) {
return null;
}
return new SimpleAuthenticationInfo(user, user.getPassWord(),
ByteSource.Util.bytes(user.getUserId()), getName());
}
/**
* 此方法必须重写,只有重写了才可以使用自己的token
*/
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof UserToken;
}
/**
* 如果需要用shiro缓存授权信息,每次请求都会走AuthorizingRealm中的getAuthorizationInfo方法,如果配置了使用了缓存,
* 这两句代码(Object key = getAuthorizationCacheKey(principals); info = cache.get(key);)会首先从缓存
* 中取授权信息,因为用了spring session,默认的取缓存的方法是得到之前登录成功的PrincipalCollection principals,
* 但是因为每次都是从spring session表中去反序列化得到此对象,所以每次的对象都是新的,
* 导致每次从缓存中取都取不到,现在重写此方法,将key改成每次登录后的登录名称,类型是String,这样cache.get(key)
* 时,比较的是String的equals方法,则只要登录名称不变就能取到缓存中的值。
*
* @param principals 登录成功的凭证(user信息)
* @return 从
*/
@Override
protected Object getAuthorizationCacheKey(PrincipalCollection principals) {
MallUserInfo userInfo = (MallUserInfo) principals.getPrimaryPrincipal();
return userInfo.getUserName();
}
}
使用自定义的token必须重写supports方法,如果要实现记住我等功能,自定义的token一定要继承自UsernamePasswordToken。
自定义过滤器
public class LoginFilter extends FormAuthenticationFilter {
/**
* 创建token
*
* @param request 请求
* @param response 返回
* @return userToken
*/
@Override
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
try {
//获取用户名\密码\图片验证码
String username = request.getParameter("username").trim();
String password = request.getParameter("password");
String verifyCode = request.getParameter("verifyCode").trim();
String clientRandom = request.getParameter("clientRandom");
String serverRandom = request.getParameter("serverRandom");
if (password == null || password.isEmpty()) {
LogUtil.warn("create token failed...miss password");
} else if (username.isEmpty()) {
LogUtil.warn("create token failed...miss username");
} else {
return new UserToken(username, sipDecryptor.decrypt(serverRandom, clientRandom, password), verifyCode);
}
} catch (DecryptionException e) {
LogUtil.error("create token failed...decrypt password failed", e);
}
return null;
}
/**
* 所有请求都会经过的方法。
*/
@Override
protected boolean onAccessDenied(ServletRequest request,
ServletResponse response) throws Exception {
if (isLoginRequest(request, response)) {
if (isLoginSubmission(request, response)) {
Session oldSession = SecurityUtils.getSubject().getSession();
//获取用户名、图片验证码
String username = request.getParameter("username").trim();
String verifyCode = request.getParameter("verifyCode").trim();
SavedRequest savedRequest = (SavedRequest) oldSession.getAttribute("shiroSavedRequest");
String randomCode = (String) oldSession.getAttribute("randomCode");
// 判断图形验证码是否正确
if (randomCode == null || !randomCode.equals(verifyCode)) {
oldSession.setAttribute("errorMsg", "图形验证码输入有误");
return true;
} else if (!checkLoginFailCount(username, host, oldSession)) {
// 判断在一定的时间范围内用户是否可以登录
return true;
} else {
oldSession.stop();
Session session = SecurityUtils.getSubject().getSession();
session.setAttribute("shiroSavedRequest", savedRequest);
//调用认证
return executeLogin(request, response);
}
} else {
// allow them to see the login page ;)
return true;
}
} else {
// 不是登录请求
saveRequestAndRedirectToLogin(request, response);
return false;
}
}
/**
* 主要是针对登入成功的处理方法。
* 可在这定义一些登陆成功时返回的数据
*/
@Override
protected boolean onLoginSuccess(AuthenticationToken token,
Subject subject, ServletRequest request, ServletResponse response)
throws Exception {
Session session = SecurityUtils.getSubject().getSession();
UserInfo user = (UserInfo) subject.getPrincipal();
session.setAttribute("userName", user.getUserName());
session.setAttribute("userId", user.getUserId());
issueSuccessRedirect(request, response);
return false;
}
/**
* 主要是处理登入失败的方法
*/
@Override
protected boolean onLoginFailure(AuthenticationToken token,
AuthenticationException e, ServletRequest request,
ServletResponse response) {
Session session = SecurityUtils.getSubject().getSession();
if (e instanceof IncorrectCredentialsException) {
session.setAttribute("errorMsg", "密码输入错误");
} else if (e instanceof UnknownAccountException) {
session.setAttribute("errorMsg", "该用户不存在");
} else {
session.setAttribute("errorMsg", "系统异常,请联系管理员");
}
setFailureAttribute(request, e);
return true;
}
}
isAccessAllowed:判断是否登录。在登录的情况下会走此方法,此方法返回true直接访问控制器
onAccessDenied:是否是拒绝登录。没有登录的情况下会走此方法
如果isAccessAllowed方法返回True,则不会再调用onAccessDenied方法,如果isAccessAllowed方法返回Flase,则会继续调用onAccessDenied方法。而onAccessDenied方法里面则是具体执行登陆的地方。
onLoginSuccess:主要是针对登入成功的处理方法。可在这定义一些登陆成功时返回的数据
onLoginFailure:主要是处理登入失败的方法。可在这定义一些登陆失败时返回的数据