实现自己的Realm
实现自己的Realm时,需要实现shiro中的Realm接口。
String getName(); //返回一个唯一的 Realm 名字 ;
boolean supports(AuthenticationToken token); //判断此 Realm 是否支持此 Token;
AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException; //根据 Token 获取认证信息 ;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.Realm;
public class MyReam implements Realm {
public String getName() {
return "myRealm1";
}
public boolean supports(AuthenticationToken authenticationToken) {
// 限制数据源只支持用户名和密码
return authenticationToken instanceof UsernamePasswordToken;
}
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String username = (String) authenticationToken.getPrincipal();
String password = new String((char[]) authenticationToken.getCredentials());
if(!"test".equals(username)){
throw new UnknownAccountException("用户名不正确");
}
if(!"123456".equals(password)){
throw new IncorrectCredentialsException("密码错误");
}
return new SimpleAuthenticationInfo(username,password,getName());
}
}
DefaultSecurityManager练习
DefaultSecurityManager securityManager = new DefaultSecurityManager();
ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
authenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
securityManager.setAuthenticator(authenticator);
ModularRealmAuthorizer realmAuthorizer = new ModularRealmAuthorizer();
realmAuthorizer.setPermissionResolver(new WildcardPermissionResolver());
securityManager.setAuthorizer(realmAuthorizer);
securityManager.setRealm(new MyReam());
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("test","123456");
try {
subject.login(token);
System.out.println("登录成功");
if(subject.isAuthenticated()){
System.out.println("登录成功");
if(subject.hasRole("admin")){
System.out.println("拥有admin角色");
}else{
System.out.println("拥有普通用户角色");
}
if(subject.isPermitted("search")){
System.out.println("拥有搜索权限");
}else{
System.out.println("没有搜索权限");
}
if(subject.isPermitted("search")){
System.out.println("拥有搜索权限");
}else{
System.out.println("没有搜索权限");
}
}
} catch (AuthenticationException e) {
// e.printStackTrace();
System.out.println("用户名或密码错误");
}
System.out.println(subject.isAuthenticated());
subject.logout();
// realmAuthorizer.set
// securityManager.setRealm();
}
输出信息