How to get a token, to consume API users and get a user by email?
// IDP client registration
@Bean
ClientRegistration clientRegistration(
@Value("${spring.security.oauth2.client.provider.idp.token-uri}") String token_uri,
@Value("${spring.security.oauth2.client.registration.idp.client-id}") String client_id,
@Value("${spring.security.oauth2.client.registration.idp.client-secret}") String client_secret,
@Value("${spring.security.oauth2.client.registration.idp.scope}") String scope,
@Value("${spring.security.oauth2.client.registration.idp.authorization-grant-type}") String authorizationGrantType
) {
return ClientRegistration
.withRegistrationId("okta")
.tokenUri(token_uri)
.clientId(client_id)
.clientSecret(client_secret)
.scope(scope)
.authorizationGrantType(new AuthorizationGrantType(authorizationGrantType))
.build();
}
and then i have this:
@Override
public LoginRequest validateEmail(Login login) {
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
.principal("idp")
.build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
// Get the token from the authorized client object
OAuth2AccessToken accessToken = Objects.requireNonNull(authorizedClient).getAccessToken();
String apiUrl = issuer_uri + "api/v1/users/?q="+login.getEmail();
System.out.println("API URL: " + apiUrl);
// Add the JWT to the RestTemplate headers
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + accessToken.getTokenValue());
HttpEntity request = new HttpEntity(headers);
// Make the actual HTTP GET request
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(
apiUrl,
HttpMethod.GET,
request,
String.class
);