'Resolving OAuth2AuthorizedClient as a Spring bean
I have a controller that is autowired with many services. These services are HTTP restful calls that retrieve data from various data sources, but these services are protected with OAuth2.0.
I am trying to use Spring Security to implement a client-credentials flow that will allow these services to securely retrieve data from these protected data sources, but am having some difficulty in resolving the OAuth2AuthorizedClient data object at the service layer.
I've been trying to resolve the authorized client via the @RegisteredOAuth2AuthorizedClient annotation:
public void setAuthorizedClient(
@RegisteredOAuth2AuthorizedClient("azure") OAuth2AuthorizedClient authorizedClient) {
ClientRegistration clientRegistration =
this.clientRegistrationRepository.findByRegistrationId("azure");
System.out.println(clientRegistration);
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
jwtToken = accessToken.getTokenValue();
}
Is it possible to resolve the OAuth2AuthorizedClient as a Spring bean that can then be injected into another bean?
Or is there a better way of architecting such a system?
Thanks!
Solution 1:[1]
Bit of an old question but I just solved this for myself so here goes:
You can create a @Component that returns the OAuth2AuthorizedClient for you, and inject that where you need it. Here is an example approach:
- Create a provider Component class
- Inject the readily available OAuth2AuthorizedClientService bean to your class
- Create a method that uses the service in order to return the OAuth2AuthorizedClient
- Inject your provider class to your Controller
Example:
@Component
public class OAuth2AuthorizedClientProvider {
@Autowired
private OAuth2AuthorizedClientService clientService;
public OAuth2AuthorizedClient getClient() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
return clientService.loadAuthorizedClient(oauthToken.getAuthorizedClientRegistrationId(), oauthToken.getName());
}
and then OAuth2AuthorizedClientProvider is used in a controller like so:
@RestController
public class Endpoint {
@Autowired
private final OAuth2AuthorizedClientProvider oauth2AuthorizedClientProvider;
@GetMapping("/mymethod")
public String mymethod() {
return oauth2AuthorizedClientProvider.getClient().getAccessToken();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gstoupis |
