GitHub:github.com/baiyuliang/…

In the last part, login authentication and authorization were completed, so the function of authorization has not been reflected. In this part, what are the uses after authorization combined with Shiro permission tags? ! Following the previous chapter, after successful login:

We can try clicking on the following modules and get a 4xx error because we haven’t added pathmaps yet:

@Configuration
public class AppConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // The browser requests are mapped to the corresponding page (ViewName represents the corresponding HTML)
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/reg").setViewName("reg");
        registry.addViewController("user/userlist").setViewName("user/userlist");
        registry.addViewController("user/add").setViewName("user/add");
        registry.addViewController("user/edit").setViewName("user/edit");
        registry.addViewController("/level1").setViewName("level1/index");
        registry.addViewController("/level2").setViewName("level2/index");
        registry.addViewController("/level3").setViewName("level3/index"); }}Copy the code

There’s a little hole in why you always add mappings… When shiro tags are used on HTML pages, only HTML pages that have been mapped are valid (get user information from shiro tag attributes)! Also, note that the mapping name must not conflict with the mappingURL you wrote in the Controller. For example, we may have specified the method in the UserController earlier:

@RequestMapping("/user")
public class UserController {

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Integer id) {
        returnuserService.getUserById(id); }}Copy the code

Then this method will follow:

registry.addViewController("user/userlist").setViewName("user/userlist");
Copy the code

Conflict! Because they use the same route “user”, the system can’t recognize which one you are using when calling, and will report an error! (The default access is from UserController first. For example, if you type http://xxx/user/userlist, it will prompt you that the data type is incorrect and cannot be passed as a string type.)

Now, if we use admin to log in (the user,role,permission table should be configured, the difference between different roles can be obtained), now we open the permission test module 1, 2, 3 can be opened normally, because we have assigned the page access permission to corresponding roles in ShiroConfig:

     map.put("/level1/**"."anyRoleFilter[user,admin,superadmin]");
     map.put("/level2/**"."anyRoleFilter[admin,superadmin]");
     map.put("/level3/**"."anyRoleFilter[superadmin]");
Copy the code

Level1 level1 resources, user,admin, and superadmin can be accessed. Level2 level2 resources, only admin,superadmin can access; Level3 resources accessible only to superadmin;

Currently, I have table USER in my database:

The role ids are 1(superadmin),2(admin), and 3(user).

Log in with admin account, then the opening effect is shown as follows:

Change the account baiyuliang, whose role is admin. Permission tests 1 and 2 are ok, but open 3:

Select * from test where user = ‘test’ and user = ‘test’;

This means that the resource restrictions we configured for role access are in effect! Now open the user management module:

If there is an error, it is possible that you did not write the user list interface:

@Repository
public interface UserRepository extends JpaRepository<User.Integer> {

    User findByUsername(String username);

    Page<User> findAll(Specification<User> spec, Pageable pageable);

}
Copy the code
public interface UserService extends BaseService {

    User getUserByName(String username);

    ResponseData getUserList(Integer page,Integer limit);

    ResponseData logout(a);
}
Copy the code
    @Override
    public ResponseData getUserList(Integer page, Integer limit) {
        ResponseData responseData = new ResponseData();
        Specification<User> specification = (Specification<User>) (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        Pageable pageable = PageRequest.of(page - 1, limit);
        Page<User> userPage = userRepository.findAll(specification, pageable);
        responseData.setCode(1);
        responseData.setMsg("Obtaining user list succeeded");
        responseData.setData(toList((int) userPage.getTotalElements(), userPage.getContent()));
        return responseData;
    }


    @Override
    public ResponseData logout(a) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new ResponseData(1."Exit successful");
    }

    public Map<String, Object> toList(int total, List list) {
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("total", total);
        return map;
    }
Copy the code

Note that the getUserList method is paginated and can be downloaded for project reference. It is not the focus of this article, so I will not explain too much!

Continue to look at the above image, we can see that admin has the permission to add, edit and delete the baiyuliang and test accounts:

See the difference? The superadmin role can be added, edited, and deleted. The admin role can be added, edited, but not deleted. The user role only has the permission to view!

What is the process of this judgment?

1. In our Shiro authorization method:

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Role role = roleService.getRoleById(user.getRoleId());
        simpleAuthorizationInfo.addRole(role.getName());// Roles: superadmin,admin,user
        Permission permission = permissionService.getPermissionByRoleId(role.getId());;
        simpleAuthorizationInfo.addStringPermission(permission.getName());// Add permissions
        return simpleAuthorizationInfo;
    }
Copy the code

According to the login user, add the role and corresponding permissions to it!

2. In the HTML page, introduce shiro tags:

<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
Copy the code

Shiro :hasAnyRoles=”superadmin,admin” : shiro:hasAnyRoles=”superadmin”

 <script type="text/html" id="toolbar">
     <div class="layui-btn-container" shiro:hasAnyRoles="superadmin,admin">
         <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add">add</button>
         <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete" shiro:hasRole="superadmin">delete</button>
     </div>
 </script>
Copy the code

Or shiro: hasRole = “superadmin” :

 <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete" shiro:hasRole="superadmin">delete</a>
Copy the code

In fact, I only use character judgment here. For more information about Shiro’s attributes, see the tips:

Easy to understand, you need to use what attributes, you can directly use!

<shiro:principal property="username"/>
Copy the code

Principal is the information that shows the login user. This is the information that you saved when you performed Shiro authentication:

Property = user; property = user; property = user; For more information on Shiro usage and configuration, as well as the use of Shiro tags, please refer to the documentation.