2023-04-25

Spring - rest template authenticate each request with a custom jwt

I have a spring boot app where I need to query an external api which is protected by the bearer token.

First i need to query the auth api for the jwt token like

POST https://some-external-api.com/api/auth/signin
{
    "username": "MyApp",
    "password": "PASSWORD"
}

I receive a response like:

{
    "access_token": "eyJ....",
    "token": "eyJ....",
    "validFrom": "2023-04-21T09:16:50.000Z",
    "validTo": "2023-04-28T09:16:50.000Z",
    "tokenType": "bearer",
    "expires": "2023-04-28T09:16:50.000Z",
    "token_type": "bearer"
}

where token and access_token fields contain the same jwt token with a payload that looks like

{
  "unique_name": "MyApp",
  "role": [
    "Reader",
    "MyApp"
  ],
  "nbf": 1682068610,
  "exp": 1682673410,
  "iat": 1682068610
}

Then I am adding this jwt token to every request using a rest template interceptor. I'd like to ask what's the best way to manage this token in spring - I don't want to implement my own token storage etc. I'd like to use some ready solution.

In my app I have a similar code where the api is protected by the oauth2 and I use something like

public class Oauth2AuthInterceptor implements ClientHttpRequestInterceptor {

    private final ClientRegistration clientRegistration;
    private final OAuth2AuthorizedClientManager manager;

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        final OAuth2AuthorizeRequest oAuth2AuthorizeRequest = OAuth2AuthorizeRequest
            .withClientRegistrationId(clientRegistration.getRegistrationId())
            .principal("myAppAuth")
            .build();
        final OAuth2AuthorizedClient client = manager.authorize(oAuth2AuthorizeRequest);
        if (isNull(client)) {
            throw new IllegalStateException("client credentials flow on " + clientRegistration.getRegistrationId() + " failed, client is null");
        }
        request.getHeaders().add(HttpHeaders.AUTHORIZATION, "bearer " + client.getAccessToken().getTokenValue());
        return execution.execute(request, body);
    }

Is it possible to customize this default oauth2 mechanism to be able to reuse it with my custom jwt auth endpoint ?



No comments:

Post a Comment