Skip to content

please provide an implementation of the bearer token support that works OOTB with Spring Security #378

@joshlong

Description

@joshlong

something like this would work

/**
*  @author Josh Long 
*/
public class OAuth2AuthorizedClientBearerTokenAuthenticationInterceptor
           extends BearerTokenAuthenticationInterceptor {

        static class SecurityContextAwareSupplier implements Supplier<String> {

            private final OAuth2AuthorizedClientManager authorizedClientManager;

            SecurityContextAwareSupplier(OAuth2AuthorizedClientManager authorizedClientManager) {
                this.authorizedClientManager = authorizedClientManager;
            }

            @Override
            public String get() {
                if ( SecurityContextHolder
                        .getContextHolderStrategy()
                        .getContext()
                        .getAuthentication() instanceof OAuth2AuthenticationToken auth2AuthenticationToken) {
                    var clientId = auth2AuthenticationToken.getAuthorizedClientRegistrationId();
                    var oauthAuthorizationRequest = OAuth2AuthorizeRequest
                            .withClientRegistrationId(clientId)
                            .principal(auth2AuthenticationToken)
                            .build();
                    var client = this.authorizedClientManager.authorize(oauthAuthorizationRequest);
                    return Objects.requireNonNull(client)
                           .getAccessToken().getTokenValue();

                }
                throw new IllegalStateException("No authenticated user");
            }
        }

        public OAuth2AuthorizedClientBearerTokenAuthenticationInterceptor( 
                  OAuth2AuthorizedClientManager authorizedClientManager) {
            super(new SecurityContextAwareSupplier(authorizedClientManager));
        }
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions