shiro框架的认证机制是基于securityManager的
认证流程:
1.创建securityManager对象并指定realm,此处我使用了自定义的realm
org.apache.shiro.mgt.SecurityManager securityManager = new DefaultSecurityManager(new MyRealm());
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
自定义realm的代码
public class MyRealm extends AuthorizingRealm{
private String username = "zs";
private String password = "123";
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
String uname = (String) token.getPrincipal();
String pw = new String((char[])token.getCredentials());
AuthenticationInfo info;
if(username.equals(uname)&&password.equals(pw)){
//成功后手动封装一个登陆信息类
info = new SimpleAuthenticationInfo(uname,pw,getName());
return info;
}else{
throw new UnknownAccountException();
}
2.创建token对象.通常实用usernameAndPasswordToken来构建
AuthenticationToken token = new UsernamePasswordToken("zst","123");
3.调用subject对象中的login方法.
try {
subject.login(token);
} catch (AuthenticationException e) {
System.out.println("用户名或密码错误");
}
shiro框架做了什么呢?
首先在调用login方法后会将令牌和subject对象交给securityManager来进行认证
然后会交给authenticator验证身份,调用doAuthenticate方法
通过realm对象完成验证
验证完成后生成登录成功对象