Customizing the Token Response Format in Spring Security OAuth2

This article explains how to override Spring Security OAuth2's default /oauth/token endpoint to return a unified response structure by redefining the TokenEndpoint and optionally the CheckTokenEndpoint, providing complete Java code examples and implementation details.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Customizing the Token Response Format in Spring Security OAuth2

In Spring Security OAuth2 the default token response from /oauth/token returns a JSON structure that often does not match a system's unified response format. The article shows how to customize this response to align with a standard format containing fields such as code, data, and msg.

Two main approaches are discussed: using AOP to intercept and modify the response, or redefining the endpoint itself. The article recommends the second, more elegant method, which requires understanding the underlying source code of Spring Security.

The TokenEndpoint class, annotated with @FrameworkEndpoint, defines the GET and POST mappings for /oauth/token. By creating a new controller that implements the same mapping and delegates to the original TokenEndpoint, the response can be wrapped in a custom result object.

@RequestMapping(value = "/oauth/token", method = RequestMethod.GET)
public ResponseEntity<OAuth2AccessToken> getAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {}

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

The custom controller is defined as follows:

@Api(value = "OAuth接口")
@RestController
@RequestMapping("/oauth")
@Slf4j
public class AuthController implements InitializingBean {
    @Autowired
    private TokenEndpoint tokenEndpoint;
    private OAuthServerWebResponseExceptionTranslator translate;

    /**
     * Override /oauth/token to return a unified data format
     */
    @PostMapping(value = "/token")
    public ResultMsg<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        OAuth2AccessToken accessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        return ResultMsg.resultSuccess(accessToken);
    }
}

Because the original exception translator becomes ineffective after overriding the endpoint, the article notes that global exception handling should be added to capture authentication‑related errors.

The same technique can be applied to the /oauth/check_token endpoint by redefining it in a similar controller, as shown below:

@Api(value = "OAuth接口")
@RestController
@RequestMapping("/oauth")
@Slf4j
public class AuthController implements InitializingBean {
    @Autowired
    private CheckTokenEndpoint checkTokenEndpoint;
    private OAuthServerWebResponseExceptionTranslator translate;

    /**
     * Override /oauth/check_token to return a unified format
     */
    @PostMapping(value = "/check_token")
    public ResultMsg<Map<String, ?>> checkToken(@RequestParam("token") String value) {
        Map<String, ?> map = checkTokenEndpoint.checkToken(value);
        return ResultMsg.resultSuccess(map);
    }
}

The article concludes that redefining the endpoints provides a clean, Spring‑compatible way to customize token responses, while AOP solutions would require additional parameter parsing and response wrapping.

Readers are encouraged to test the implementation themselves and explore further customizations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentOAuth2spring-securityToken Customization
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.