shiro-Authorization

The last blog post summarized the identity authentication in Shiro. This article mainly summarizes the Authorization function in Shiro, that is, authorization. as follows: 


1. The core elements of authorization authentication

Permission authentication, that is, access control, is to control who can access which resources in the application. In authority authentication, the three core elements are: authority, role and user:

 

Permission: the right to operate resources, such as access to a page, and the right to add, modify, delete, and view the data of a module; 
role: refers to the role played by the user, a A role can have multiple permissions; 
user: In Shiro, it represents the user who accesses the system, that is, the Subject authentication subject mentioned in the previous blog post

 

The relationship between them can be represented by the following diagram: 

 

 

 A user can have multiple roles, and different roles can have different permissions or the same permissions. For example, there are three roles now, 1 is a common role, 2 is also a common role, and 3 is an administrator. Role 1 can only view information, and role 2 can only add information. Administrators can also delete information, similar to this .

 

 

2.1 Role-Based Access Control

  That is, the authorization process is done by judging roles, which roles can do this, which roles can do this, and so on. It has the following API:

 

method effect
hasRole(String roleName) Determine whether the role has access rights, return boolen
hasRoles(List<String> roleNames) Determine whether these roles have access rights, return boolean[]
hasAllRoles(Collection<String> roleNames) Determine whether these roles have access rights, return boolean

 

 

 For these three APIs, make a brief description. The first one is very simple. You can pass in a role to determine whether you have access to the role. The second method is to pass in a set of roles, and then Shiro will use the set according to the set. Make a judgment for each role in the , and put the result of each judgment into the boolean[] array, in the same order as the roles in the set; the third method also passes in a set of roles, the difference is that return boolean type, it must be true if all roles in the collection are present, otherwise it is false. 

  The usage is as follows:

Subject currentUser = SecurityUtils.getSubject();
if (currentUser.hasRole("administrator")) {
    //show the admin button or do administrator's things
} else {
    //don't show the button?  Grey it out? or others...
}

 In addition to these three APIs, Shiro also provides a check API. The difference from the above is that has-xxx will return boolean type data for judgment, while check-xxx will not return anything. If the verification is successful, continue Handle the code below, otherwise an exception will be thrown which can be used to handle by catching the exception. The API is as follows:

 

method effect
checkRole(String roleName) If the judgment fails, an AuthorizationException is thrown
checkRoles(String... roleNames) If the judgment fails, an AuthorizationException is thrown
checkRoles(Collection<String> roleNames) If the judgment fails, an AuthorizationException is thrown

 

 Similar usage is as follows:

 

Subject currentUser = SecurityUtils.getSubject();
//guarantee that the current user is a bank teller and
//therefore allowed to open the account:
currentUser.checkRole("bankTeller");
openBankAccount();

 

2.2 Permission-based access control

  Permission-based access control and role-based access control are the same in principle, but the API is different. I will not explain too much. The API is as follows:

 

method effect
isPermitted(String perm) Determine whether there is this permission, return boolen
isPermitted(List<String> perms) Determine whether there are these permissions, return boolean[]
isPermittedAll(Collection<String> perms) Determine whether there are these permissions, return boolean
checkPermission(String perm) If the judgment fails, an AuthorizationException is thrown
checkPermissions(String... perms) If the judgment fails, an AuthorizationException is thrown
checkPermissionsAll(Collection<String> perms) If the judgment fails, an AuthorizationException is thrown

 

3. Permission authentication sample code

  Whether it is identity authentication or authority authentication, you first need to create a SecurityManager factory, SecurityManager, so first create a new tool class to do this.

public class ShiroUtil {

    public static Subject login(String configFile, String username,
            String password) {

        // 读取配置文件,初始化SecurityManager工厂
        Factory<SecurityManager> factory = new IniSecurityManagerFactory(configFile);
        // 获取securityManager实例
        SecurityManager securityManager = factory.getInstance();
        // 把securityManager实例绑定到SecurityUtils
        SecurityUtils.setSecurityManager(securityManager);
        // 得到当前执行的用户
        Subject currentUser = SecurityUtils.getSubject();
        // 创建token令牌,用户名/密码
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try{
            // 身份认证
            currentUser.login(token);   
            System.out.println("身份认证成功!");
        }catch(AuthenticationException e){
            e.printStackTrace();
            System.out.println("身份认证失败!");
        }
        return currentUser;
    }
}

 

提供一个静态方法,返回当前用户,在应用程序中我们直接调用这个类中的静态方法即可返回当前认证的用户了。 
  maven中的pom.xml文件内容和上一节一样的,不再赘述。 
  Shiro的配置文件shiro.ini:

#用户,role表示各个角色
[users]
csdn1=123,role1,role2,role3
csdn2=123,role1,role2

#定义不同角色都拥有哪些权限
[roles]
role1=user:select
role2=user:add,user:update
role3=user.delete

 

角色认证:

public class RoleTest {

    @Test
    public void testHasRole() {

        String configFile = "classpath:shiro.ini";
        String username = "csdn2";
        String password = "123";
        Subject currentUser = ShiroUtil.login(configFile, username, password);

        //测试hasRole
        System.out.println(currentUser.hasRole("role2")? "有role2这个角色" : "没有role2这个角色");

        //测试hasRoles
        boolean[] results = currentUser.hasRoles(Arrays.asList("role1","role2","role3"));
        System.out.println(results[0]? "有role1这个角色" : "没有role1这个角色");
        System.out.println(results[1]? "有role2这个角色" : "没有role2这个角色");
        System.out.println(results[2]? "有role3这个角色" : "没有role3这个角色");

        //测试hasAllRoles     System.out.println(currentUser.hasAllRoles(Arrays.asList("role1","role2","role3")));

        currentUser.logout();
    }

    @Test
    public void testCheckRole() {

        String configFile = "classpath:shiro.ini";
        String username = "csdn2";
        String password = "123";
        Subject currentUser = ShiroUtil.login(configFile, username, password);

//      currentUser.checkRole("role3");//没有返回值。有就不报错,没有就会报错
//      currentUser.checkRoles(Arrays.asList("role1","role2","role3")); //同上
        currentUser.checkRoles(Arrays.asList("role1","role2")); //同上

        currentUser.logout();
    }
}

 

权限认证和角色认证的测试一样的,我就不再赘述了。当然了,这里只是单纯的测试,实际中,认证完了后还要做一些具体的业务逻辑处理。

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326127241&siteId=291194637