Does the Token have to be in the request header? The answer is definitely no. This article will share the parsing process of Spring Security OAuth2 from the source point of view, and the application scenario of the extension point.

This section describes the Token resolution process

When we use Spring Security OAuth2, we generally need to put the token requested by the authentication authority in the request header to request the target interface, as shown in figure 1 below

Spring security oauth2 retrives this token through an interceptor to complete the conversion of the token to the current UserDetails.

  • OAuth2AuthenticationProcessingFilter.doFilter
public class OAuth2AuthenticationProcessingFilter{ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { try { // 1. Authentication Authentication = Tokenextractor.extract (request); If (authentication == null) {// If the pre-login status is null, The stateless login to empty the if (stateless && isAuthenticated ()) {SecurityContextHolder. ClearContext (); }} else {// 2. Use the token to authenticate the login Provier Authentication authResult = authenticationManager.authenticate(authentication); / / 3. Login successful logical eventPublisher. PublishAuthenticationSuccess (authResult); SecurityContextHolder.getContext().setAuthentication(authResult); }} Catch (OAuth2Exception failed) {// Spring Event... return; } chain.doFilter(request, response); }}Copy the code

Let’s focus on the first step to parse the token and assemble the pre-login object based on the user’s request

Look at the default implementation BearerTokenExtractor

public class BearerTokenExtractor implements TokenExtractor { @Override public Authentication extract(HttpServletRequest  request) { // 1. TokenValue = extractToken(Request); if (tokenValue ! = null) {/ / 2. Create an authentication return PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(tokenValue, ""); return authentication; } return null; } Protected String extractToken(HttpServletRequest Request) {// 1.1 Obtain token from request header first extractHeaderToken(request); // if the requested token is not present, If (token == null) {token = request.getParameter(oAuth2Accesstoken.access_token); if (token == null) {token = request.getParameter(oAuth2Accesstoken.access_token); } return token; }}Copy the code

The extension point

    1. Rich access to token channels, personalized processing. For example, the X-legacy-Token for nuggets does not have to be Authorization

    1. Request parameters with access_token parameters can also be properly parsed

    1. rewriteBearerTokenExtractorResolve a problem where a request carrying a token will be blocked regardless of whether the interface is set to permitAll

RBAC permission management system PigBearerTokenExtractor extension based on Spring Boot 2.3.0, Spring Cloud Hoxton & Alibaba, OAuth2