自定义Realm
若想自定义realm只需要实现AuthorizingRealm这个类
这个AuthorizingRealm是个抽象类,其中它自己有doGetAuthorizationInfo(授权)这个方法,它继承的AuthentcatingRealm中有doGetAuthenticationInfo(认证)这个方法
package com.jing.realm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class CustomRealm extends AuthorizingRealm {
// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 获取用户名
String username = (String) token.getPrincipal();
System.out.println("username = " + username);
// 这里直接将用户名写死了,进行判断
if ("admin".equals(username)) {
// 创建一个AuthenticationInfo接口的实现类SimpleAuthenticationInfo
// 参数1:用户名,参数2:密码,参数3:realmName
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("admin", "123456",this.getName());
return authenticationInfo;
}
return null;
}
}
package com.jing.realm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
public class CustomAuthenticatorRealm {
public static void main(String[] args) {
DefaultSecurityManager securityManager = new DefaultSecurityManager();
securityManager.setRealm(new CustomRealm());
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456");
try {
boolean authenticated = subject.isAuthenticated();
System.out.println("authenticated = " + authenticated);
subject.login(token);
authenticated = subject.isAuthenticated();
System.out.println("authenticated = " + authenticated);
} catch (AuthenticationException e) {
e.printStackTrace();
}
}
}