编程知识 cdmana.com

Introduction to spring security (2)

There's a little water in the last article , In this issue, we directly deliver dry goods , Learn the certification process .

Let's think about it first , About SpringSecurity How to implement security permission management , Role check , Let's compare permissions and roles

//  Verify the role   visit  "/product/add"  Should have  admin  Role 
.antMatchers("/product/add").hasRole("admin");
//  visit  "/product/add"  Should have  PRODUCT_ADD  Authority 
.antMatchers("/product/add").hasAnyAuthority("PRODUCT_ADD")

SpringSecurity Verify whether the current user has such a role or permission , However, this is limited to the situation that the current project needs to be front-end and back-end at the same time , We just need to set the current permissions to SpringSecurity, for example :

/**
 *  Query permissions and put permissions into  security  in 
 *
 * @param http
 * @throws Exception
 */
public void selectPurview(HttpSecurity http) throws Exception {
    List<Purview> purviews = purviewService.selectPurview();
    for (Purview purview : purviews) {
        http.authorizeRequests()
            //  Set the permissions 
            .antMatchers(purview.getUrl()).hasAnyAuthority(purview.getAuthority());
    }
}

If you want to be a character , Then change the code for setting permissions to setting roles , Simple things don't have code , Let's take a closer look at the case when the front and rear ends are separated , How to deal with .

Who developed , See whose explanation , Look directly at SpringSecurity Official Document No 10 Chapter file , At first glance, it must be SecurityContextHolder, This class stores the details of the authenticated person , It's really vague , In fact, it is the personnel information after login .

The following is SecurityContext, You can get ,SecurityContextHolder And includes Authentication Information about the currently authenticated user

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

AuthenticationManager The authentication manager is very strong , You can provide the credentials provided by the user for authentication , You can also provide the current user from SecurityContext , Authenticated users ,Authentication It can be downloaded from SecurityContext obtain .

The Authentication contain :

  • principal- Identifying users . Use the user name / Password Authentication , Usually an example of UserDetails.
  • credentials- Usually a password . in many instances , This content will be cleared after user authentication , To make sure it doesn't leak .
  • authorities- stay GrantedAuthoritys Is that the user is granted high-level permissions . Roles or scopes are a few examples .

In this case, we can guess , If we encapsulate the user information of successful login into toekn, When he requests an interface, he passes the interceptor , Parse his information , And pass it on to SecurityContextHolder, Does that complete the verification . Such as this :

SecurityContextHolder.getContext().setAuthentication(Authentication authentication);

It's worth thinking about , How to build such a Authentication authentication object , Look back Official documents 10.1, The official document mentions :

Create a new Authentication object .Spring Security Not care Authentication What type of implementation is set on SecurityContext. Here we use TestingAuthenticationToken It's because it's very simple . A more common production scenario is UsernamePasswordAuthenticationToken(userDetails, password, authorities).

UsernamePasswordAuthenticationToken An implementation designed to simply render user names and passwords . View source code :

public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken;
public abstract class AbstractAuthenticationToken implements Authentication,CredentialsContainer;

Now it's not difficult to understand why UsernamePasswordAuthenticationToken You can build a Authentication Object .

	private final Object principal;
	private Object credentials;

	/**
	 * This constructor should only be used by <code>AuthenticationManager</code> or
	 * <code>AuthenticationProvider</code> implementations that are satisfied with
	 * producing a trusted (i.e. {@link #isAuthenticated()} = <code>true</code>)
	 * authentication token.
	 *
	 * @param principal
	 * @param credentials
	 * @param authorities
	 */
    public UsernamePasswordAuthenticationToken(Object principal, Object credentials,
                Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        super.setAuthenticated(true); // must use super, as we override
    }

That means actually , We should use this build function to build Authentication object , That is to say UsernamePasswordAuthenticationToken(principal, credentials, authorities)

Explain these three parameters in detail

  • principal Obviously, this uses final Modification cannot be modified , Therefore, the value passed must not need to be modified after authentication , for example : User information
  • credentials Information used to prevent authentication , It can be token
  • authorities Privilege set

The idea seems to be clear again , The process of certification is like this , We do login authentication , Verify account password , Generate TOEKN, Then parse the current TOEKN, Get user information , Privilege set , Used to generate Authentication, Put it in SecurityContext in , Leave the permission verification and verification to SpringSecurity management , There should be nothing wrong with this idea .

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Shao Jie]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/08/20210809183600811s.html

Scroll to Top