OAuth2 with OKTA in springboot

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
 		);

Hello,

In the code you provided what happens when you run it?
Are you authenticating and getting an access_token but the /api/v1/users call fails?

If you can provide more details.

1 Like

fail gives me a 400 bad request error

what I need is to obtain an okta token (api token) to be able to query and create users consuming the okta api from my back with springboot

What scopes were you requesting for your token, and is your Service app configured to allow use of that scope? If you’re making a GET to /users, you will need to ensure you use the okta.users.read —or okta.users.manage, if you also need to make a change to the user(s)— scope