1. Introduction

When a third party agrees to authorize it, we call redirectUri to send a receipt to our server. Our server gets an intermediate credential and authenticates again in order to obtain the Token. And this logic is in the charge of OAuth2LoginAuthenticationProvider, after the article analysis we found are done by OAuth2AuthorizationCodeAuthenticationProvider access Token of specific logic, To clarify the process today, let’s take a look at the steps Spring Security OAuth2 takes to authenticate and authorize a Token.

Note: The OAuth2 portion of this Spring Security dry goods tutorial series is in Spring Security 5.x.

2. OAuth2AuthorizationCodeAuthenticationProvider

This class is the implementation of AuthenticationProvider for the Authorization Code Grant pattern in OAuth 2.0. It is important to briefly emphasize that the AuthenticationProvider has been used many times in the Spring Security dry goods series and is very important! Be sure to take a look at the analysis and use of it, as it is an important entry point into your business to expand your authentication channels.

2.1 OAuth2AccessTokenResponseClient

In this implementation includes a OAuth2AccessTokenResponseClient member variable, it abstract through tokenUri endpoint details from the authentication server access Token. You can implement it according to the four patterns commonly used in OAuth 2.0 to achieve the ability to obtain tokens based on different strategies.

The 2.0 in the Spring Security 5 login configuration using DefaultAuthorizationCodeTokenResponseClient by default. If you want to use a custom implementation you can configure it with HttpSecurity:

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.oauth2Login()
                    .tokenEndpoint()
                / / into custom OAuth2AccessTokenResponseClient
                    .accessTokenResponseClient(authorizationCodeTokenResponseClient);
            // other omissions

        }
Copy the code

Next we see DefaultAuthorizationCodeTokenResponseClient logic to realize the access Token:

@Override
public OAuth2AccessTokenResponse getTokenResponse(OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest) {
   Assert.notNull(authorizationCodeGrantRequest, "authorizationCodeGrantRequest cannot be null");
// 1. Encapsulate the RequestEntity required to call tokenUriRequestEntity<? > request =this.requestEntityConverter.convert(authorizationCodeGrantRequest);

   ResponseEntity<OAuth2AccessTokenResponse> response;
   try {
   / / 2. Get OAuth2AccessTokenResponse through RestTemplate initiate the request
      response = this.restOperations.exchange(request, OAuth2AccessTokenResponse.class);
   } catch (RestClientException ex) {
      OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE,
            "An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response:" + ex.getMessage(), null);
      throw new OAuth2AuthorizationException(oauth2Error, ex);
   }

  / / 3. Parse ResponseEntity return value OAuth2AccessTokenResponse organization
   OAuth2AccessTokenResponse tokenResponse = response.getBody();

   if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) {
  
      // originally requested by the client in the Token Request
      tokenResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse)
            .scopes(authorizationCodeGrantRequest.getClientRegistration().getScopes())
            .build();
   }

   return tokenResponse;
}
Copy the code

The approach here is similar to the Payment Spring Boot request approach for my other open source project, which consists of three steps:

  1. Tissue parametersRequestEntity.
  2. RestOperationsInitiate a request.
  3. parsingResponseEntityOrganizes the return value.

If some of the 2.0 authentication server access Token you can achieve OAuth2AccessTokenResponseClient way is special.

3. Summary

OAuth2AccessTokenResponseClient is the core of OAuth2AuthorizationCodeAuthenticationProvider points. Just figure out what it does and how it works. Here we summarize OAuth2AuthorizationCodeAuthenticationProvider certification process:

  1. No credit was grantedOAuth2AuthorizationCodeAuthenticationTokenIs the status of the.
  2. throughOAuth2AccessTokenResponseClientrequestThe 2.0Obtaining an Authentication ServerTokenAnd other information.
  3. Assemble certified creditsOAuth2AuthorizationCodeAuthenticationTokenTo return.

This clears up the OAuth 2.0 login process, which you can learn to critique through a series of articles. I am: code farmers small fat brother, a lot of attention, access to practical programming dry goods.

Follow our public id: Felordcn for more information

Personal blog: https://felord.cn