登陆流程:
使用Shiro进行安全管理,首先先要自定义一个Realm类来继承AuthorizingRealm,并实现其两个方法,分别是doGetAuthorizationInfo、doGetAuthenticationInfo,前者是自定义授权操作方法,后者是自定义认证方法。
**
* 使用salt和md5对密码进行加密
*/
public class CustomerRealm2 extends AuthorizingRealm {
/**
* 授权方法
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
/**
* 认真方法
* @param token
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String principal = (String) token.getPrincipal();
if ("sdl".equals(principal)){
//使用MD5+salt进行密码加密,并且进行1024次散列,提高安全性
return new SimpleAuthenticationInfo(principal,"21ababebd65267d72d6b32e2e8392793", ByteSource.Util.bytes("0dex"),this.getName());
}
return null;
}
}
使用自定义realm方法进行身份认证
/**
* 测试随机盐和md5算法
*/
public class TestDiyRealm2 {
public static void main(String[] args) {
//创建安全管理器
DefaultSecurityManager defaultSecurityManage=new DefaultSecurityManager();
//设置自定义的realm
CustomerRealm2 customerRealm2 = new CustomerRealm2();
//设置md5加密
HashedCredentialsMatcher hashedCredentialsMatcher=new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("MD5");
//设置散列次数
hashedCredentialsMatcher.setHashIterations(1024);
//给customerRealm2设置密码匹配器
customerRealm2.setCredentialsMatcher(hashedCredentialsMatcher);
defaultSecurityManage.setRealm(customerRealm2);
//给全局安全工具类设置安全管理器
SecurityUtils.setSecurityManager(defaultSecurityManage);
//获取主体
Subject subject = SecurityUtils.getSubject();
/*Md5Hash hash=new Md5Hash("123","0dex",1024);
System.out.println(hash.toHex());*/
//创建令牌
UsernamePasswordToken token=new UsernamePasswordToken("sdl","123");
try{
subject.login(token);
System.out.println("登陆成功");
}catch (UnknownAccountException e){
System.out.println("未知账户");
}catch (IncorrectCredentialsException e){
System.out.println("密码错误");
}
}
}