Integrate spring security and customize the verification code instance in spring boot

Final effect

1. Realize page access permission restriction 2. Distinguish user roles and distinguish page permissions according to roles 3. Store user information and role information in the database 4. Customize authentication code

The effects are as follows:

1. Exemption verification page

2. Landing page

When the user is not logged in, accessing any page with permission requirements will automatically jump to the login page.

3. Pages that need to be logged in to view

After logging in, the user can normally access the page resources and correctly display the user login name:

4. Users have different roles. You can specify that some pages are only allowed to be used by people with corresponding user roles

4.1. Pages that only admin thinks users can view (insufficient permissions)

4.2. Only the page that admin thinks users can view (the permission is satisfied)

The implementation steps are described in detail below.

code implementation

Maven introduces dependency

In POM Introducing spring security dependency into XML

Configure spring security

In spring, to configure and use spring security, you only need to declare interception rules without modifying too many process details, At the same time, you can customize the main implementation interfaces (user information userdetails, user information acquisition service userdetailsservice, authentication tool authenticationprovider) in the authentication process. The rest of the processes will be automatically taken over by spring, which is very convenient.

Start configuration

Add the specific implementation class of websecurityconfigureradapter under the project package to realize the startup configuration of spring security

The code is as follows:

URL interception configuration

The URL interception configuration can be configured in websecurityconfig in the previous section, but this method is applicable to the configuration in the general direction. The specific special path can also be configured in the annotation of @ controller.

As follows:

User and role table

In this example, users and roles can have a one to many relationship, so users and roles can be divided into two tables. In some examples, it is also possible to write users and permissions on the same table.

Custom validation

In the spring security tutorial of spring boot, the default user name, password and permission are specified in the code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>