添加 Realm
log.info("authenticationToken:"+authenticationToken);
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String loginName = token.getUsername();
User user = new User(loginName,null);
//根据用户名获取用户信息
user = userService.login(user);
if(null==user){
throw new UnknownAccountException("用户名不存在");
}
//取出盐并编码
ByteSource salt = ByteSource.Util.bytes(loginName);
SimpleAuthenticationInfo simpleAuthenticationInfo= new SimpleAuthenticationInfo(loginName,user.getPassWord(),salt,getName());
return simpleAuthenticationInfo;在这里插入代码片
加密
public class ShiroUtil {
/**
*
* @param encryptedStr
* @return
*/
public static final String MD5(final String useName,final String passWord){
ByteSource salt = ByteSource.Util.bytes(useName);
SimpleHash simpleHash=new SimpleHash(ShiroConstant.ENCRYPTION_MD5, passWord, salt, ShiroConstant.ENCRYPTION_NO);
return simpleHash.toHex();
}
}
登录controller
Subject subject = SecurityUtils.getSubject();
//如果登录用户没有通过身份验证
if(!subject.isAuthenticated()){
//封装成token对象
UsernamePasswordToken token = new UsernamePasswordToken(username,passWord);
token.setRememberMe(true);
try {
subject.login(token);
}catch (AuthenticationException e){
log.info("登录失败"+e.getMessage());
}
}
加密配置
bean id="securityRealm" class="com.ali.pims.realms.ShiroRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!--md5加密-->
<property name="hashAlgorithmName" value="MD5"></property>
<!--加密次数-->
<property name="hashIterations" value="2"></property>
</bean>
</property>
</bean>