This is an original article. Welcome any form of reprint, but please be sure to note the source cold https://lltx.github.io.

How do OAuth 2.0 get tokens

  • The following uses password mode as an example to describe how to obtain a Token
curl --location --request POST 'http://oauth-server/oauth/token' \
--header 'Authorization: Basic dGVzdDp0ZXN0' \
--data-urlencode 'username=admin' \
--data-urlencode 'password=123456' \
--data-urlencode 'scope=server' \
--data-urlencode 'grant_type=password'
Copy the code
  {
   "access_token":"2YotnFZFEjr1zCsicMWpAA",
   "token_type":"example",
   "expires_in":3600,
   "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
   "example_parameter":"example_value"
 }
Copy the code
  • To access OAuth 2.0 / OAuth /token source code is as follows

TokenEndpoint.postAccessToken

@RequestMapping(value = "/oauth/token", method=RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam
Map<String, String> parameters){
  ...
  return getResponse(token);
Copy the code

}

Customizes the default token address

  • As mentioned above, by default we need to access /oauth/token access, that is, all the service system “login” interface becomes this address, how to customize the path address without rewriting this interface?

  • Spring Security OAuth2 provides us with rich configuration, we can in AuthorizationServerConfigurerAdapter set all the built-in custom pathMapping Endpoint (the Endpoint) path

  • Overrides the original /oauth/token with /pig4cloud/login as follows: “Note that this overrides the original path once configured”

@EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) { endpoints .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST) .pathMapping("/oauth/token","/pig4cloud/login"); }}Copy the code
  • Getting the token address becomes the following
curl --location --request POST 'http://oauth-server/pig4cloud/login' \
--header 'Authorization: Basic dGVzdDp0ZXN0' \
--data-urlencode 'username=admin' \
--data-urlencode 'password=123456' \
--data-urlencode 'scope=server' \
--data-urlencode 'grant_type=password'
Copy the code

Source analysis

  • How does Spring Security OAuth2 implement this endpoint customization configuration?

  • AuthorizationServerEndpointsConfigurer to be written to customized HandlerMapping

private FrameworkEndpointHandlerMapping frameworkEndpointHandlerMapping() { if (frameworkEndpointHandlerMapping == null)  { frameworkEndpointHandlerMapping = new FrameworkEndpointHandlerMapping(); frameworkEndpointHandlerMapping.setMappings(patternMap); frameworkEndpointHandlerMapping.setPrefix(prefix); frameworkEndpointHandlerMapping.setInterceptors(interceptors.toArray()); } return frameworkEndpointHandlerMapping; }Copy the code
  • The SpringMVC DispatcherServlet will route according to the new rules