Shiro入门学习三
认证
身份认证流程参考官网Authentication Sequence
流程如下,参考自第二章 身份验证——《跟我学Shiro》:
- 首先调用
Subject.login(token)
进行登录,其会自动委托给Security Manager,调用之前必须通过SecurityUtils. setSecurityManager()
设置; - SecurityManager负责真正的身份验证逻辑;它会委托给Authenticator进行身份验证;
- Authenticator才是真正的身份验证者,Shiro API中核心的身份认证入口点,此处可以自定义插入自己的实现;
- Authenticator可能会委托给相应的AuthenticationStrategy进行多Realm身份验证,默认ModularRealmAuthenticator会调用AuthenticationStrategy进行多Realm身份验证;
- Authenticator会把相应的token传入Realm,从Realm获取身份验证信息,如果没有返回/抛出异常表示身份验证失败了。此处可以配置多个Realm,将按照相应的顺序及策略进行访问。
JavaSE例子
单个realm
创建一个MapRealm
实现Realm
接口,主要要实现3个方法:
public String getName()
返回realm的名称public boolean supports(AuthenticationToken token)
判断此Realm是否支持此Tokenpublic AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)
根据Token获取认证信息
如下所示的MapRealm
public class MapRealm implements Realm{
private static Map<String, String> users;
static{
users = new HashMap<String, String>();
users.put("kh", "123");
users.put("laozhag", "123");
}
@Override
public String getName() {
return "MapRealm";
}
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof UsernamePasswordToken;
}
@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = token.getPrincipal().toString();
String password = new String((char[])(token.getCredentials()));
System.out.println("username: " + username + " password: "+password);
if (!users.containsKey(username)) {
throw new UnknownAccountException("用户名出错");
}
if (!password.equals(users.get(username))) {
throw new IncorrectCredentialsException("密码出错");
}
AuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName());
return info;
}
}
然后,在shiro.ini
中配置securityManager
的realms
,这里先配置一个:
[main]
mapRealm=com.wz.shiro.realm.MapRealm
securityManager.realms = $mapRealm
Junit测试过程如下:
@Test
public void testBase(){
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject