Moment For Technology

Spring Security: client OAuth2 authorization request entry

Posted on Sept. 23, 2022, 9:44 a.m. by Donna Morgan
Category: The back-end Tag: java Spring Cloud

1. Introduction

In Spring Security actual combat: OAuth2 third party authorization first experience in this article I first to OAuth2.0 involved in some common concepts introduced, and then directly through a DEMO to let you feel the OAuth2.0 third party authorization function. Today we're going to take a step-by-step look at how this works.

2. Get to the source

http://localhost:8082/oauth2/authorization/gitee

The above request URL is the starting point for the client's third-party authentication operation we mentioned in the previous article. The default format is {baseUrl}/ oAuth2 /authorization/{clientRegistrationId}, ClientRegistrationId represents a third-party identity, which can be wechat, Alipay and other open platforms. In this case, Gitee. The user clicks on the request and begins the authorization journey. If everybody is the small white that begins from zero, it is to want to explore the mechanism among them step by step from this entrance for certain. Spring Security must have intercepted/oAuth2 /authorization before enabling oAuth2 related processing logic. Then go to the source! Search from the source! IDEA shortcut key CTRL + SHIFT + R to search results globally.

Sure enough, I found three places. Make a note of each one!

OAuth2AuthorizationRequestRedirectWebFilter

Start with the first OAuth2AuthorizationRequestRedirectWebFilter, it implements the Spring Webflux WebFilter interface, it's clearly a Webflux, this will be useful, if you use Webflux But it's not what we use now.

DefaultOAuth2AuthorizationRequestResolver

The second one is a default OAuth2 authorization request parser. Sometimes the name is good enough to know the general purpose of this thing, I have to say that a good framework detail is very good. It implements the interface OAuth2AuthorizationRequestResolver:

public interface OAuth2AuthorizationRequestResolver {

   / * * * parsing encapsulation OAuth2AuthorizationRequest * / from it
   OAuth2AuthorizationRequest resolve(HttpServletRequest request);

   / * * * from it and clientRegistrationId parsing encapsulation OAuth2AuthorizationRequest * /
   OAuth2AuthorizationRequest resolve(HttpServletRequest request, String clientRegistrationId);

}
Copy the code

That is, when we request/oAUTH2 /authorization, DefaultOAuth2AuthorizationRequestResolver Will be extracted from the corresponding it/oauth2 authorization data encapsulation to OAuth2AuthorizationRequest for further use in the request object.

Note: The default interception identifier/oAuth2 /authorization is also customizable.

OAuth2AuthorizationRequest

Here simple mention OAuth2AuthorizationRequest encapsulates our article described some concepts of OAuth2 parameters, follow-up the request class we will use it.

public final class OAuth2AuthorizationRequest implements Serializable {
    private static final long serialVersionUID = 520L;
    private String authorizationUri;
    private AuthorizationGrantType authorizationGrantType;
    private OAuth2AuthorizationResponseType responseType;
    private String clientId;
    private String redirectUri;
    private SetString scopes;
    private String state;
    private MapString, Object additionalParameters;
    private String authorizationRequestUri;
    private MapString, Object attributes;
    // Other methods are omitted
}
Copy the code

OAuth2AuthorizationRequestRedirectFilter

This is the only clue left, as soon as I see it inherits OncePerRequestFilter I know it must be him. Even its member variable contains used to resolve OAuth2AuthorizationRequestResolver OAuth2 request. Here we are on the right track to start analyzing the filter. Here is the core filtering logic. This is the logic we want to know how OAuth2 authorization requests are intercepted and processed.

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {

   try {
      OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestResolver.resolve(request);
      if(authorizationRequest ! =null) {
         this.sendRedirectForAuthorization(request, response, authorizationRequest);
         return; }}catch (Exception failed) {
      this.unsuccessfulRedirectForAuthorization(request, response, failed);
      return;
   }

   try {
      filterChain.doFilter(request, response);
   } catch (IOException ex) {
      throw ex;
   } catch (Exception ex) {
      // Check to see if we need to handle ClientAuthorizationRequiredException
      Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(ex);
      ClientAuthorizationRequiredException authzEx = (ClientAuthorizationRequiredException) this.throwableAnalyzer
         .getFirstThrowableOfType(ClientAuthorizationRequiredException.class, causeChain);
      if(authzEx ! =null) {
         try {
            OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestResolver.resolve(request, authzEx.getClientRegistrationId());
            if (authorizationRequest == null) {
               throw authzEx;
            }
            this.sendRedirectForAuthorization(request, response, authorizationRequest);
            this.requestCache.saveRequest(request, response);
         } catch (Exception failed) {
            this.unsuccessfulRedirectForAuthorization(request, response, failed);
         }
         return;
      }

      if (ex instanceof ServletException) {
         throw (ServletException) ex;
      } else if (ex instanceof RuntimeException) {
         throw (RuntimeException) ex;
      } else {
         throw newRuntimeException(ex); }}}Copy the code

The doFilterInternal process is as follows:

According to the process, if you want to make clear Spring Security OAuth2 is how to redirect to a third party to further study of sendRedirectForAuthorization method, based on analysis of cause of space I will be in the next article.

3. Summary

Today we take a step by step look at the OAuth2 authorized processing entry and take a look at the role of several key components and the core interceptor's interception logic. Follow-up we will layer on layer to step by step to figure out its operation process, do not go away, lock: code farmer xiao Fat brother step by step learning Spring Security OAuth2.

Follow our public id: Felordcn for more information

Personal blog: https://felord.cn

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.