CustomRealm
public class CustomRealm extends AuthorizingRealm{
@Override
public void setName(String name) {
super.setName("customRealm");;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userCode = (String)token.getPrincipal();
String password = "111111";
if(!userCode.equals("zhangsansan")) {
return null;
}
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userCode, password,this.getName());
return simpleAuthenticationInfo;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
return null;
}
}
ini配置文件相当于spring的注入数据库实现
[main]
#自定义realm
customRealm=cn.dinggc.shiro.realm.CustomRealm
#将realm设置到securityManager,相当于spring注入
securityManager.realms=$customRealm
自定义Realm测试
@Test
public void testCustomRealm() {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-realm.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "111111");
try {
subject.login(token);
} catch (AuthenticationException e) {
e.printStackTrace();
}
boolean isAuthenticated = subject.isAuthenticated();
System.out.println("是否认证通过: " + isAuthenticated);
subject.logout();
isAuthenticated = subject.isAuthenticated();
System.out.println("是否认证通过: " + isAuthenticated);
}