我有一个 spring boot 应用程序,我需要在其中查询受不记名令牌保护的外部 api。
首先我需要查询 auth api 以获取 jwt 令牌
POST https://some-external-api.com/api/auth/signin
{
"username": "MyApp",
"password": "PASSWORD"
}
我收到这样的回复:
{
"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"
}
其中
token
和 access_token
字段包含相同的 jwt 令牌,其有效负载看起来像
{
"unique_name": "MyApp",
"role": [
"Reader",
"MyApp"
],
"nbf": 1682068610,
"exp": 1682673410,
"iat": 1682068610
}
然后我使用 rest 模板拦截器将这个 jwt 令牌添加到每个请求。我想问一下在春季管理这个令牌的最佳方法是什么——我不想实现我自己的令牌存储等。我想使用一些现成的解决方案。
在我的应用程序中,我有一个类似的代码,其中 api 受 oauth2 保护,我使用类似的代码
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);
}
是否可以自定义此默认 oauth2 机制,以便能够将其与我的自定义 jwt 身份验证端点一起重用?