Spring Security OAuth 2.0 issuing token interface address customization

How to obtain token in OAuth 2.0

  • Take password mode as an example to obtain 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'
  • The original process actually accesses the source code of / oauth/token provided by OAuth 2.0 as follows


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


Custom default get token address

  • As mentioned above, by default, we need to access / oauth/token. That is to say, the "login" interface of all business systems becomes this address. How to customize the path address without rewriting this interface.

  • Spring Security OAuth2 provides us with rich configurations. We can set the custom pathMapping of all built-in Endpoint paths in the AuthorizationServerConfigurerAdapter

  • Use / pig4cloud/login to overwrite the original / oauth/token as follows. Note that the overwrite will fail once the original path is configured

public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
				.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
				.pathMapping("/oauth/token","/pig4cloud/login");	}
  • 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'

Source code analysis

  • How does spring security oauth2 implement this endpoint custom configuration?

  • AuthorizationServerEndpointsConfigurer is written to custom HandlerMapping

private FrameworkEndpointHandlerMapping frameworkEndpointHandlerMapping() {
  if (frameworkEndpointHandlerMapping == null) {
    frameworkEndpointHandlerMapping = new FrameworkEndpointHandlerMapping();
  return frameworkEndpointHandlerMapping;
  • Spring MVC dispatcher servlet will route according to the new rules

Project recommendation: Welcome to RBAC permission management system of Spring Cloud and Spring Security OAuth2

Tags: Programming Spring curl

Posted on Fri, 08 May 2020 11:59:57 -0400 by wing_zero