javaspringspring-securityaccess-token

Get the OAuth2/OIDC access token with every request in Spring


I'm trying to enable multi-tenancy for a previously single-user system. The application used to run on a local server and had a relatively simple frontend baked in.

Now I want to allow multiple users to simultaneously use it in a cloud environment. I went ahead and implemented Auth2 with OIDC and PKCE to redirect users to an external Auth Provider. What I want now is that for every request, the user sends his Access token with the request in order for me to decide what data to provide with the answer.

I could not figure out how to obtain that data, as it seems that the spring framework (by default) only sends the ID token with the request. I suspect the fact that my software would simultaneously be the client and the resource server has something to do with it.

This is my first question, so I'm very happy to modify or extend my question if I've forgotten anything.

What I've tried to far:

I've used Postman to verify that the three tokens, ID token, refresh token and access token are issued correctly and can be retrieved with my credentials.

I tried getting the access token from the request itself. Any parameters (like @AuthenticationPrincipal OidcUser oidcUser) in the controller that include the token, however, are only showing the ID token and not the access token.

Getting the token via the OAuth2AuthorizedClientService does not work either, same problem, as I can only get the ID token, but not the access token.


Update #1, 13.12.2022/11:40: I am using PingOne by PingIdentity as the authentication provider and the following dependencies are or might be related or helpful to this matter:


Solution

  • Thanks to those who tried to help me, but eventually I figured it out myself.

    I extended my Controllers by two attributes: OAuth2AuthenticationToken authentication and HttpServletRequest request.

    Controller-methods signature

    Also, I @Autowired in the OAuth2AuthorizedClientRepository oAuth2AuthorizedClientRepository.

    Autowired client-repository

    This then allows the following call returning the value of the accessToken: (oAuth2AuthorizedClientRepository.loadAuthorizedClient(myClientRegistrationId, authentication, request)).client.getAccessToken().getTokenValue();.

    After that, it's just parsing the token and retrieving the values using JWTParser.parse() and provided methods from the JWT-result.

    Personal note: Don't do the parsing and retrieving value parts in your controller to keep any more complex logic out of it.

    I hope this helps somebody!