Shiro 自定义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.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import java.util.*;
public class CustomRealm extends AuthorizingRealm {
Map<String, String> map = new HashMap<String, String>();
{
map.put("yan", "123");
super.setName("customRealm");
}
//授权
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = (String) principals.getPrimaryPrincipal();
Set roles = getRolesByUsername(username);
Set permissions = getPermissionsByUsername(username);
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.setRoles(roles);
simpleAuthorizationInfo.setStringPermissions(permissions);
return simpleAuthorizationInfo;
}
private Set getPermissionsByUsername(String username) {
Set lists = new HashSet();
lists.add("user:add");
lists.add("user:delete");
return lists;
}
private Set getRolesByUsername(String username) {
Set lists = new HashSet();
lists.add("admin");
lists.add("user");
return lists;
}
//认证
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//获取用户名
String username = (String) token.getPrincipal();
//数据库查询密码
String password = getPasswordByUsername(username);
if(password ==null){
return null;
}
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("yan","123","customRealm");
return simpleAuthenticationInfo;
}
//模拟获取密码
private String getPasswordByUsername(String username) {
return map.get(username);
}
}
Realm 测试类:
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
public class CustomRealmTest {
@Test
public void testAuthentication(){
CustomRealm customRealm = new CustomRealm();
//构建SecurityManager
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(customRealm);
//主体提交认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject();
//主体提交认证请求
UsernamePasswordToken token = new UsernamePasswordToken("yan","123");
subject.login(token);
subject.checkRole("admin");
}
}