package com.arp.shiro;
import java.util.HashSet;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import com.hqyj.po.User;
import com.hqyj.service.UserService;
public class MyRealm extends AuthorizingRealm{
@Autowired
private UserService service;
//认证方法
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// TODO Auto-generated method stub
// System.out.println("realm:"+token.hashCode());
// System.out.println(token.getPrincipal());
//用户名:admin,密码为123
// if(!token.getPrincipal().equals("admin")){
// throw new UnknownAccountException();
// }
// UsernamePasswordToken utoken=(UsernamePasswordToken)token;
// String pwd=new String(utoken.getPassword());
// if(!(pwd.equals("123"))){
// throw new IncorrectCredentialsException();
// }
UsernamePasswordToken utoken=(UsernamePasswordToken)token;
String pwd=new String(utoken.getPassword());
User user=service.findByUsernameAndPwd((String)token.getPrincipal(), pwd);
if(user==null){
throw new IncorrectCredentialsException();
}
SimpleAuthenticationInfo info=new
SimpleAuthenticationInfo(token.getPrincipal(),
token.getCredentials(), getName());
return info;
}
public static void main(String[] args) {
// hashAlgorithmName:加密算法
// Credentials:原始密码
// Salt:盐值
// hashIterations:加密次数
Object Salt="zyl";
SimpleHash simplehash=
new SimpleHash("Md5", "123456", Salt, 1024);
System.out.println(simplehash);
//038bdaf98f2037b31f1e75b5b4c9b26e,admin
//90b2b8819937e37ab28c05b94877ba12 ,zhh,123456
}
//用于授权
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// TODO Auto-generated method stub
Set<String> roles=new HashSet<String>();
roles.add("user");
if(principals.getPrimaryPrincipal().equals("admin")){
roles.add("admin");
}
SimpleAuthorizationInfo info=
new SimpleAuthorizationInfo();
for(String role:roles){
info.addRole(role);
}
return info;
}
}