Shiro Tutorial (1): Permission management based on url

1. Authority management

1.1  What is rights management

Basically, systems involving user participation are subject to rights management. Rights management belongs to the category of system security. Rights management realizes the control of user access to the system. According to security rules or security policies , users can access and can only access their authorized users. resource.

Rights management includes two parts: user identity authentication and authorization, referred to as authentication and authorization. For resources that need access control, users must first undergo identity authentication. After the authentication is passed, users can access the resources only after they have access rights to the resources.

 

1.2  User Authentication

1.2.1  Concept

Identity authentication is the process of judging whether a user is a legitimate user. The most commonly used simple authentication method is that the system checks whether the user name and password entered by the user are consistent with the user name and password stored in the system to determine whether the user's identity is correct. For systems such as fingerprints , show fingerprints; for card-swiping systems such as hardware keys, you need to swipe your card.

 

 

1.2.2  Username and password authentication process

 

1.2.3  Key Objects

 

The following key objects need to be understood in the flow chart above:

 

Subject: subject

The user who accesses the system, the subject can be a user, a program, etc., and the authentication is called the subject;

 

 Principal: identity information

It is the identification of the subject for authentication. The identification must be unique, such as user name, mobile phone number, email address, etc. A subject can have multiple identities, but must have a primary principal.

 

 credential: credential information

It is security information that only the subject knows, such as passwords, certificates, etc.

 

 

1.3  Authorization

1.3.1  Concept

Authorization, or access control, controls who can access which resources. After authentication, the subject needs to be assigned permissions to access the resources of the system. Some resources cannot be accessed without permission.

 

1.3.2  Authorization Process

 The orange in the figure below is the authorization process.

 

1.3.3  Key Objects

 

Authorization can be simply understood as who performs the How operation on what(which):

 Who, the subject (Subject), the subject needs to access the resources in the system.

 What, that is, resources (Resource), such as system menus, pages, buttons, class methods, system commodity information, etc. Resource includes resource type and resource instance, for example, commodity information is resource type, commodity with type t01 is resource instance, and commodity information with serial number 001 also belongs to resource instance.

 How, permission/permission (Permission), specifies the subject's permission to operate the resource. It is meaningless to leave the resource, such as user query permission, user addition permission, calling permission of a class method, modification permission of user number 001, etc. Through the permissions, you can know which operation permissions the subject has on which resources.

Permissions are divided into coarse-grained and fine-grained. Coarse-grained permissions refer to resource types, while fine-grained permissions refer to resource instances.

 

The relationship between subjects, resources, and permissions is as follows:

 

 

 

1.3.4  Permission Model

 

The subjects, resources, and permissions in the previous section are represented by the data model.

 

Subject (account, password)

Resource (resource name, access address)

Permissions (authority name, resource id)

role (role name)

Role and permission relationship (role id, permission id)

Subject and role relationship (subject id, role id)

 

 

As shown below:

 

 

 

As shown below:

 

Usually, in enterprise development, the resource and permission tables are combined into one permission table, as follows:

Resource (resource name, access address)

Permissions (authority name, resource id)

Combined as:

Permissions (authority name, resource name, resource access address)

 

 

The above figure is often referred to as a general model of authority management. However, enterprises will modify the above figure according to the characteristics of the system itself during development. However, users, roles, permissions, user-role relationships, and role-authority relationships need to be understood.

 

 

1.3.5  Permission assignment

When assigning authority to the subject, the subject is only allowed to operate the resources within the scope of authority, for example, assigning the user u01 the right to modify the product, and the u01 user can only modify the product.

The data of permission assignment usually needs to be persisted, and the table is created according to the above data model and the user's permission information is stored in the database.

 

 

1.3.6  Permission Control

The user can operate the resources within the scope of the authority after the user has the authority. The system does not know whether the subject has the access authority and needs to control the user's access.

 

 

1.3.6.1  Role-Based Access Control

RBAC's role-based access control (Role-Based Access Control) is role-centered access control. For example, if the subject's role is the general manager, he can query enterprise operation reports, query employee salary information, etc. The access control process is as follows:

 

 

The judgment logic code in the above figure can be understood as:

if(main.hasRole("general manager role id")){

Check salary

}

 

 

Disadvantages: The granularity of access control based on roles is relatively coarse. If the roles required for salary query in the above figure are changed to general manager and department manager, then the judgment logic needs to be modified to "judging whether the role of the subject is general manager or department manager" , the system scalability is poor.

Modify the code as follows:

if(subject.hasRole("general manager role id") || subject.hasRole("department manager role id")){

Check salary

}

 

1.3.6.2  Resource-based access control

RBAC resource-based access control (Resource-Based Access Control) is resource-centered access control. For example, the subject must have the permission to query salary information to query employee salary information, etc. The access control process is as follows:

 

 

The judgment logic code in the above figure can be understood as:

if(main.hasPermission("Query salary permission ID")){

Check salary

}

 

Advantages: When the system is designed, the permission ID for querying wages is defined. Even if the roles required for querying wages are changed to general manager and department manager, it is only necessary to add “inquiry salary information permission” to the permission list of “department manager role” to judge The logic does not need to be modified, and the system has strong scalability.

 

Rights Management Solutions

2.1  Coarse and fine particle size

2.1.1  What is Coarse Grain and Fine Grain

The management of resource types is called coarse-grained authority management, which only controls menus, buttons, and methods. For example, a user has the authority to manage user and export order details. The control of resource instances is called fine-grained permission management, that is, permissions at the data level. For example, the user is only allowed to modify the employee information of the department, and the user is only allowed to export the order details created by himself.

 

2.1.2  How to achieve coarse-grained and fine-grained

For coarse-grained authority management, it is easy to perform system architecture-level functions, that is, system function operations use unified coarse-grained authority management.

For fine-grained permission management, it is not recommended to make system architecture-level functions, because data-level control is the business requirement of the system. With the change of business requirements, business functions are likely to change. It is recommended that data-level permissions be Personalized development is controlled at the business layer. For example, users are only allowed to modify the product information created by themselves. You can add verification implementation to the service interface. The service interface needs to pass in the identity of the current operator, which is compared with the identity of the creator of the product information. Modification of product information is allowed.

 

2.2  Based on url interception

Based on url interception is a commonly used rights management method in enterprises. The realization idea is: configure each url of system operation in the permission table, map the permissions to roles, assign roles to users, and filter the functions of users to access the system. The filter obtains the url accessed by the user, and as long as the accessed url is the url in the role assigned by the user, it will continue to access.

As shown below:

 

 

 

 

2.3  Using the Rights Management Framework

For permission management, basically every system has it. Using the permission management framework to complete the development of permission management functions can save system development time, and the permission management framework provides complete authentication and authorization functions, which is conducive to system expansion and maintenance, but learning the permission management framework It requires cost, so it is very important to choose a simple and efficient rights management framework.

 

Implementation based on url interception

3.1  Environment Preparation

jdk:1.7.0_72

web container: tomcat7

System framework: springmvc3.2.0+mybatis3.2.7 (refer to springmvc lesson plan for details)

Front UI: jquery easyUI1.2.2

 

3.2  Database

 

Create mysql5.1 database

Create user tables, role tables, permission tables, role permission relationship tables, and user role relationship tables.

Import the script, first import shiro_sql_talbe.sql and then import shiro-sql_table_data.sql

 

 

 

3.3  activeUser user identity class

When the user logs in successfully, the activeUser information is recorded and the activeUser is stored in the session.

 

public class ActiveUser implements java.io.Serializable {

private String userid;//User id

private String usercode;// user account

private String username;// username

 

private List<SysPermission> menus;// 菜单

private List<SysPermission> permissions;// 权限


 

 

 

3.4 anonymousURL.properties

anonymousURL.properties public access address, can be accessed without authentication.

3.5 commonURL.properties

commonURL.properties public access address, which can be accessed through identity authentication without assigning permissions.

 

 

3.6  User Authentication Interceptor

Use the springmvc interceptor to intercept user authentication. If the user is not logged in, it will jump to the login page. This function can also be implemented using filter.

 

public class LoginInterceptor implements HandlerInterceptor {

 

// execute before entering the controller method

// Usage scenarios: such as authentication verification interception, user permission interception, if the interception is not released, the controller method will no longer be executed

@Override

public boolean preHandle(HttpServletRequest request,

HttpServletResponse response, Object handler) throws Exception {

 

// Check whether the user access is a public resource address (can be accessed without authentication)

List<String> open_urls = ResourcesUtil.gekeyList("anonymousURL");

 

// url accessed by the user

String url = request.getRequestURI();

for (String open_url : open_urls) {

if (url.indexOf(open_url) >= 0) {

// Release if the access is to a public address

return true;

}

}

 

// Check if the user's identity is authenticated

HttpSession session = request.getSession();

ActiveUser activeUser = (ActiveUser) session.getAttribute("activeUser");

if (activeUser != null) {

// The user has logged in and authenticated, let go

return true;

}

// Jump to the login page

request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,

response);

return false;

}


 

 

 

3.7  User authorization interceptor

Use the springmvc interceptor to intercept user access urls. If the url accessed by the user does not have assigned permissions, it will jump to the unauthorized operation prompt page (refuse.jsp). This function can also be implemented using filter.

 

public class PermissionInterceptor implements HandlerInterceptor {

 

// execute before entering the controller method

// Usage scenarios: such as authentication verification interception, user permission interception, if the interception is not released, the controller method will no longer be executed

// To be executed before entering the action method

@Override

public boolean preHandle(HttpServletRequest request,

HttpServletResponse response, Object handler) throws Exception {

// TODO Auto-generated method stub

// User access address:

String url = request.getRequestURI();

 

// Check whether the user access is a public resource address (can be accessed without authentication)

List<String> open_urls = ResourcesUtil.gekeyList("anonymousURL");

// url accessed by the user

for (String open_url : open_urls) {

if (url.indexOf(open_url) >= 0) {

// Release if the access is to a public address

return true;

}

}

//Get the user's public access address from the session (authentication can be accessed without assigning permissions)

List<String> common_urls = ResourcesUtil.gekeyList("commonURL");

// url accessed by the user

for (String common_url : common_urls) {

if (url.indexOf(common_url) >= 0) {

// If the access is to the public address, then let go

return true;

}

}

// Get user permission information from session

 

HttpSession session = request.getSession();

 

ActiveUser activeUser = (ActiveUser) session.getAttribute("activeUser");

 

// Take out the permission url in the session

// Get user permission to operate

List<SysPermission> permission_list = activeUser.getPermissions();

// Check whether the user's access address is within the user's permission scope

for (SysPermission sysPermission : permission_list) {

String permission_url = sysPermission.getUrl();

if (url.contains(permission_url)) {

return true;

}

}

 

// jump to the page

request.getRequestDispatcher("/WEB-INF/jsp/refuse.jsp").forward(

request, response);

return false;

}


 

 

3.8  User login

The user enters the user account and password to log in, and the login successfully records the user's identity information (user account, password, authority menu, authority url, etc.) into the activeUser class and writes it into the session.

 

3.8.1 controller

//User login submit

@RequestMapping("/loginsubmit")

public String loginsubmit(HttpSession session,String usercode,String password,String randomcode) throws Exception{

 

//check verification code

//Get the correct verification code from the session

String validateCode = (String)session.getAttribute("validateCode");

if(!randomcode.equals(validateCode)){

//Throw exception: verification code error

throw new CustomException("Verification code error!");

}

//User authentication

ActiveUser activeUser = sysService.authenticat(usercode, password);

//record session

session.setAttribute("activeUser", activeUser);

return "redirect:first.action";

}


 

 

3.8.2  service interface

 

/**

 *

 * <p>

 * Title: authenticat

 * </p>

 * <p>

 * Description: User authentication

 * </p>

 *

 * @param usercode

 * user account

 * @param password

 * user password

 * @return ActiveUser user identity information

 * @throws Exception

 */

public ActiveUser authenticat(String usercode, String password)

throws Exception;

 

// Query users by account

public SysUser findSysuserByUsercode(String usercode) throws Exception;

 

// Get permission based on user id

public List<SysPermission> findSysPermissionList(String userid)

throws Exception;

 

// Get menu based on user id

public List<SysPermission> findMenuList(String userid) throws Exception;

If the article is inappropriate, please correct me. You can also pay attention to my WeChat public account: 好好学java, to obtain high-quality resources.

Guess you like

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