本文是基于springboot版本的,不多逼逼,直接上码
1、依赖
<!--shiro-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.8.0</.version>
</dependency>
2、配置类
package com.duanqwei.springcloud.shiro;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* shiro配置类
*/
@Configuration
@Slf4j
public class ShiroConfig {
/**
* realm对象注入
*/
@Bean
public MyRealm myRealm(){
MyRealm myRealm=new MyRealm();
//设置加密方式
myRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return myRealm;
}
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String,String> filterMap = new LinkedHashMap<>();
//认证拦截
filterMap.put("/login","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
return shiroFilterFactoryBean;
}
/**
* 上面密码都是采用的明文方式进行比对的。
* shiro提供给我们一种密码加密的方式
* @return
*/
@Bean(name = "credentialsMatcher")
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
// 散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashAlgorithmName("MD5");
//加密次数
hashedCredentialsMatcher.setHashIterations(1024);
// // storedCredentialsHexEncoded默认是true,此时用的是密码加密用的是Hex编码;false时用Base64编码
hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
return hashedCredentialsMatcher;
}
/**
* 配置核心安全事务管理器
* @param myRealm
* @return
*/
@Bean(name = "securityManager")
public SecurityManager securityManager(@Qualifier("myRealm") MyRealm myRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//设置自定义realm.
securityManager.setRealm(myRealm);
//配置记住我
//securityManager.setRememberMeManager(rememberMeManager());
//配置redis缓存管理器
//securityManager.setCacheManager(getEhCacheManager());
//配置自定义session管理
//securityManager.setSessionManager(sessionManager());
return securityManager;
}
/**
* cookie管理对象;记住我功能
*
* @return
*/
public CookieRememberMeManager rememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
// 使用自定义的序列化类
//cookieRememberMeManager.setSerializer(new MySecSerializer<>());
cookieRememberMeManager.setCookie(rememberMeCookie());
//rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 192 256 位)
cookieRememberMeManager.setCipherKey(GenerateCipherKey.generateNewKey());
return cookieRememberMeManager;
}
/**
* cookie对象;
*
* @return
*/
public SimpleCookie rememberMeCookie() {
// 这个参数是cookie的名称,对应前端的checkbox的name = rememberMe
SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
// 记住我cookie生效时间30天 ,单位秒。 注释掉,默认永久不过期
simpleCookie.setMaxAge(2592000);
return simpleCookie;
}
@Bean(name = "lifecycleBeanPostProcessor")
public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
/**
* 解决 shiro 反序列化漏洞
*/
public static class GenerateCipherKey {
/**
* 随机生成秘钥,参考org.apache.shiro.crypto.AbstractSymmetricCipherService#generateNewKey(int)
*
* @return byte[]
*/
public static byte[] generateNewKey() {
KeyGenerator kg;
try {
kg = KeyGenerator.getInstance("AES");
} catch (NoSuchAlgorithmException var5) {
String msg = "Unable to acquire AES algorithm. This is required to function.";
throw new IllegalStateException(msg, var5);
}
// 满足合规应使用256位
kg.init(256);
SecretKey key = kg.generateKey();
return key.getEncoded();
}
}
//基于shiro自带的加密工具加密的
public static void main(String[] args) {
// 加密算法MD5
// salt盐
String password = "123456";
String md5Pwd = new SimpleHash("MD5", password,
ByteSource.Util.bytes("@cloud-duanqwei-fangkk")
, 1024).toHex(); //加密1024次
System.out.println(md5Pwd);
}
}
3、自定义Realm
package com.duanqwei.springcloud.shiro;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.duanqwei.springcloud.entity.UserInfo;
import com.duanqwei.springcloud.mapper.UserInfoMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
/**
* MyRealm
*
* @author duanqiangwei
* @date 2021/11/15 23:33
*/
public class MyRealm extends AuthorizingRealm {
@Autowired
private UserInfoMapper userInfoMapper;
@Value("${shiro.salt}")
private String salt; //加密的盐值
/**
* 授权认证
*
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
/**
* 身份认证
*
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//把AuthenticationToken转换为UsernamePasswordToken,token中储存着输入的用户名和密码
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
//获取账号
String username = userToken.getUsername() ;
//根据系统管理员账号获取系统管理员信息
UserInfo user = userInfoMapper.
selectOne(new QueryWrapper<UserInfo>().eq("user_name", username));
if (user!= null){
//principal:认证的实体信息,可以是username,也可以是数据库表对应的用户的实体对象
Object principal = user.getUserName();
//credentials:数据库中的密码
Object credentials = user.getPassword();
//realmName:当前realm对象的name,调用父类的getName()方法即可
String realmName = getName();
//盐值
ByteSource credentialsSalt = ByteSource.Util.bytes(salt);
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
return info;
}else{
throw new UnknownAccountException("不存在该用户");//没找到帐号
}
}
}
4、登陆
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
// 从SecurityUtils里边创建一个 subject
Subject subject = SecurityUtils.getSubject();
// 在认证提交前准备 token(令牌)
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// 执行认证登陆
try {
subject.login(token);
} catch (Exception e) {
e.printStackTrace();
}
if (subject.isAuthenticated()) {//认证通过
return "登录成功";
} else {
token.clear();
return "登录失败";
}
}
5、源码流程(核心代码)
//前端请求的参数,封装在token对象里
public void login(AuthenticationToken token) throws AuthenticationException {
//清空Session
clearRunAsIdentitiesInternal();
//登陆
Subject subject = securityManager.login(this, token);
Session session = subject.getSession(false);
if (session != null) {
this.session = decorate(session);
} else {
this.session = null;
}
}
//登陆校验
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
info = authenticate(token);
} catch (AuthenticationException ae) {
}
Subject loggedIn = createSubject(token, info, subject);
onSuccessfulLogin(token, info, loggedIn);
return loggedIn;
}
public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
info = doAuthenticate(token);
} catch (Throwable t) {
}
return info;
}
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
//加载所有的Realm,包含自定义的
assertRealmsConfigured();
Collection<Realm> realms = getRealms();
if (realms.size() == 1) {
return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
} else {
return doMultiRealmAuthentication(realms, authenticationToken);
}
}
//单个realm认证
protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
AuthenticationInfo info = realm.getAuthenticationInfo(token);
return info;
}
protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
CredentialsMatcher cm = getCredentialsMatcher(); //获取当前加密方式,盐值,加密次数
if (cm != null) {
if (!cm.doCredentialsMatch(token, info)) { //密码对比
}
} else {
}
}
//密码对比
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
//获取Info里面的盐值,对前端传参按照自定义Realm里的方式加密
Object tokenHashedCredentials = hashProvidedCredentials(token, info);
//获取info里的密码,处理返回
Object accountCredentials = getCredentials(info);
//比较两者,如果不一致,就会报密码不一致的错误
return equals(tokenHashedCredentials, accountCredentials);
}