自定义realm(主要就是自定义的realm要继承AuthorizingRealm 类,重写两个方法(一是认证,而是授权,两个方法一般要查询数据库,这里用的是模拟数据)

public class CustomRealm extends AuthorizingRealm {
    Map<String,String> map=new HashMap<>(16);
    {
        map.put("mark","123456");
        super.setName("customRealm");
    }
    //Principal  重要,主角的意思  ,Set集合无序,且不可重复
    @Override    //z  授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        //从数据库或者缓存中获取角色数据
        Set<String> roles=getRolesByUserName(username);
        //从数据库或者缓存中获取角色的权限数据
        Set<String> permissions=getPermissionsByUserName(username);
        //创建AuthorizationInfo授权对象
        SimpleAuthorizationInfo simpleAuthorizationInfo=
                new SimpleAuthorizationInfo();
        //设置角色
        simpleAuthorizationInfo.setRoles(roles);
        //设置权限
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    private Set<String> getPermissionsByUserName(String username) {
        //模拟数据取数据,roles的权限数据
        Set<String> permissions=new HashSet<>();
        permissions.add("user:select");
        permissions.add("user:delete");
        permissions.add("user:update");
        permissions.add("user:insert");
        return permissions;
    }

    private Set<String> getRolesByUserName(String username) {
        //模拟数据取数据,roles数据
            Set<String> roles=new HashSet<>();
            roles.add("admin");
            roles.add("user");
            return roles;
    }

    @Override   //c  认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1.从主体传过来的认证信息中,获取用户名
        String  username = (String) token.getPrincipal();
        //2.通过用户名,到数据库中获取凭证(这里不查数据库,写死)
        String password = getPasswordByUserName(username);
        if (password==null){
            return null;
        }
        //返回对象SimpleAuthenticationInfo
        SimpleAuthenticationInfo authenticationInfo=
                new SimpleAuthenticationInfo(username,password,"customRealm");
        return authenticationInfo;
    }

    //模拟数据库查凭证
    private String getPasswordByUserName(String username) {
        //从map集合获取密码
        return map.get(username);
    }
}

测试代码

public class CustomRealmTest {
    @Test
    public void testCustomRealm(){
        CustomRealm customRealm=new CustomRealm();
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(customRealm);
        SecurityUtils.setSecurityManager(defaultSecurityManager);

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("mark","123456");
        //认证
        subject.login(token);
        //授权
        subject.checkRoles("admin","user");
        subject.checkPermissions("user:select","user:update");


    }
}
01-10 11:25