Customize realm to check if the user has permissions

Write shiro-permission-realm.ini configuration file

[main]
#声明一个realm
myReal= com.feng.realm.PermissionRealm
#指定securityManager的realms实现
securityManager.realms=$myReal

Customize Realm, rewrite authorization method

public class PermissionRealm extends AuthorizingRealm {

    public String getName(){

        return "PermissionRealm";
    }

    @Override
    //授权操作
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //传入参数:principals :用户认证凭证信息
        //SimpleAuthenticationInfo:认证方法返回封装认证信息中第一个参数:用户信息(username)
        //当前登入用户名信息:用户凭证
        String username = (String) principalCollection.getPrimaryPrincipal();
        //模拟数据库,查询用户实现指定的角色,以及用户权限
        List<String> roles = new ArrayList<>();//角色集合

        List<String> permission = new ArrayList<>();//权限集合

        //假设用户在数据库中有role1角色
        roles.add("role1");
        //假设用户在数据库中拥有user:delete权限
        permission.add("user:*");

        //返回用户在数据库中的权限与角色
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        info.addRoles(roles);
        info.addStringPermissions(permission);

        return info;
    }


    @Override
    //认证操作
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //参数token:  示登入时包装的UserPasswordToken
        //通过用户名到数据库中查用户信息,封装成AuthenticationInfo对象返回,方便认证器进行对比
        //获取token中的用户名
        String username = (String)token.getPrincipal();

        //通过用户名查询数据库,将用户对应数据查询返回: 账号与密码
        //假设查询数据库返回数据是:zhangsan  666
        if (!"zhangsan".equals(username)){
            return null;
        }

        String password="666";

        //info对象表示realm登入比对信息:参数1:用户信息(真实登入中是登入对象user对象),参数2:密码 参数3:当前realm名字
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName());

        return info;
    }

Write test program

public class MyTest {

    @Test
    public void hasRole(){

        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-permission-realm.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "666");
        try {
            subject.login(token);
        }catch (Exception e){

            e.printStackTrace();
        }

        //进行授权操作时:用户必须通过认证

        //判断当前用户是否拥有某个角色:返回true表示拥有,false表示没有
        System.out.println(subject.hasRole("role1"));


        //判断用户是否拥有某个权限,返回true表示拥有
        System.out.println(subject.isPermitted("user:delete"));


    }


}
Published 48 original articles · Likes0 · Visits 282

Guess you like

Origin blog.csdn.net/qq_44971387/article/details/105351154