问题
Project: spring-security 5.2
I'm using servlet environment to do service-to-service oauth (like from @Scheduled
). I'm doing password grant for service account (corporate, don't ask me to change this, it's given). This is possibly very long running service.
Works fine, but I'm wondering what happens if refresh token becomes invalid (revoked, authrization service restart). From what I understand the RefreshTokenOAuth2AuthorizedClientProvider
will fail with exception (the refresh token has been revoked). PasswordOAuth2AuthorizedClientProvider
won't be even reached, but if it was it will be skipped becasue client has refresh token (even though it's revoked or no longer works).
From that moment all requests from the WebClient
will fail because there is no way to get hold of valid access token. The missing piece seems to be the authorized client record needs to be removed from the OAuth2AuthorizedClientService
which will result in re-doing the password grant from scratch.
My configuration of WebClient
looks as follows:
@Bean
public WebClient webClient(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientService authorizedClientService) {
AuthorizedClientServiceOAuth2AuthorizedClientManager manager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(clientRegistrationRepository, authorizedClientService);
manager.setAuthorizedClientProvider(new DelegatingOAuth2AuthorizedClientProvider(
new RefreshTokenOAuth2AuthorizedClientProvider(),
new PasswordOAuth2AuthorizedClientProvider()));
Map<String, Object> passwordAttributes = new HashMap<>();
passwordAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "NPA_username");
passwordAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "NPA_password");
manager.setContextAttributesMapper(request -> passwordAttributes);
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 = new ServletOAuth2AuthorizedClientExchangeFilterFunction(manager);
oauth2.setDefaultClientRegistrationId("oauth-service-to-service-client");
return WebClient.builder()
.filter(oauth2)
.apply(oauth2.oauth2Configuration())
.build();
}
And registration:
spring:
security:
oauth2:
client:
registration:
oauth-service-to-service-client:
provider: ...
client-id: ...
client-secret: ...
client-authentication-method: basic
authorizationGrantType: password
scope: default
client-name: Sample app - Service to service
来源:https://stackoverflow.com/questions/58604304/how-to-re-initialize-password-grant-in-spring-security-5-2-oauth