Access control based on roles or permissions in Spring Security

Access control based on roles or permissions in Spring Security

1. The code in configure (HttpSecurity http) in the SpringSecurity configuration class

Insert picture description here
In the above figure, I forgot to add .anyRequest().authenticated() after hasAnyRole(), which must be added in the formal development;
.anyRequest()
.authenticated()
The role of these two methods is to ensure All requests must undergo login verification,
except for the request in antMatchers(request).permitAll(), because if the permitAll method is called after the antMatchers method, then the request in antMatchers does not need to be logged in verification; if no .anyRequest is written ().authenticated() Then as long as it is not similar to antMatchers("request").hasRole(...) or antMatchers("request").hasAuthority(...), the request can be without login verification, (in other words, only similar to the above Only requests for login verification will be performed) and then you can access directly. We definitely don’t want this when using Spring Security, so we must remember to add .anyRequest().authenticated()

The source code of the four methods is as follows:

Insert picture description here

If you set up custom authentication login and set permissions, the situation of roles is combined together as shown in the following figure:

Insert picture description here

2. Code in the UserDetailService implementation class

The situation in the UserDetailsService implementation class is as follows:

Insert picture description here

3. Configure(AuthenticationManagerBuilder auth) method in SpringSecurity configuration class

Finally, write the authentication management method as shown below:

Insert picture description here

4. Verify login page in the browser

The verification login page in the browser is as follows:

Insert picture description here

5. Forbidden pages in the browser when there is no permission or role

If the user does not have the corresponding permissions or roles, that is, if the user object of the return method implemented in the UserDetailsService implementation class does not have the relevant permissions or methods in the User object, then when an access request appears, the browser will display the following prompt:

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45950109/article/details/112966544