Invalid Access Token - when Calling OAuth2 Protected Rest end point - Spring

hi,
I am writing a oauth2 client code which is used to call oAuth2 protected rest endpoint (basically its server-server call).i need to make a post call for it. when making a call using OAuth2RestTemplate , I am getting invalid token… not sure of whether i have to get accesstoken from okta or spring will directly inject the token automatically in the header…

Below is my spring auto configurer

spring:
      application:
        name: okta-connector
      security:
        oauth2:
          client:
            grantType: client_credentials
            clientId: 0oag3ila8dsasdfqwerIDmMjH0h7
            clientSecret: my-super-secret
            access-token-uri: https://myorg.oktapreview.com/oauth2/Default/v1/token

application.java

@EnableOAuth2Client
@SpringBootApplication
public class OktaConnectorApplication {

	public static void main(String[] args) {
		SpringApplication.run(OktaConnectorApplication.class, args);
	}
	
	@Bean
    @ConfigurationProperties("spring.security.oauth2.client")
    protected ClientCredentialsResourceDetails oAuthDetails() {
        return new ClientCredentialsResourceDetails();
    }

    @Bean
    protected OAuth2RestTemplate restTemplate() {
        return new OAuth2RestTemplate(oAuthDetails());
    }

controller:

@Controller
@RequestMapping({"/v2/Users"})
public class OktaUserController
{
	
    @Autowired
    private OAuth2RestTemplate restTemplate;

	  private static final Logger logger = LoggerFactory.getLogger(OktaUserController.class);

     @RequestMapping(value={"/{id:.*}"}, method={org.springframework.web.bind.annotation.RequestMethod.PUT})
	  @ResponseBody
	  public User updateUser(@PathVariable String id, @RequestBody User updatedUser) throws Exception
	  {
		 try {
			 if (updatedUser == null) { 
				 String userNull = context.getMessage("request.userNull.Excep", null,
							Locale.getDefault());
				 logger.error(userNull+" "+id);
				 throw new SCIMConnectorException(userNull+" "+id);
			 }
			 logger.debug("Processing the request, with the request Id -  "+id +" and for the user - "+updatedUser.getId());
		    
		    request.setUid(request.getUid().substring(0,request.getUid().indexOf("@")));

		    String url = " url of my oauth2 rest end point";
		    logger.debug("Posting the request for changing the password for the user "+request.getUid());
		    restTemplate.postForEntity(url, request, CpwRequest.class);
	        
}

}

error from logs:

018-08-31 02:55:03 : Created POST request for "https://myorg.oktapreview.com/oauth2/Default/v1/token"
2018-08-31 02:55:04 : POST request for "https://myorg.oktapreview.com/oauth2/Default/v1/token" resulted in 400 (Bad Request); invoking error handler
2018-08-31 02:55:04 : Exception while processing the request, with the message Access token denied.
2018-08-31 02:55:04 : Could not complete request
java.lang.Exception: Access token denied.

as said from above call, does spring directly injects access token when making post call or do we need to inject it by getting the access token from the resttemplate…?

any help is greatly appreciated.

Hey @marc

A couple things:

  • double check your org by hitting:
    https://myorg.oktapreview.co/oauth2/Default/.well-known/openid-configuration (updating for your domain), if you don’t get back a json doc, there is a problem with the URL.
  • make sure client_credientials is enabled for your application (from your Okta Admin Console)
  • I’m guessing you have already looked at this blog post, but if not, check it out
  • If those didn’t help, turn on wire logging for your application, and see what the body of the 400 response. (just enabling debug logging for Spring Security might help too)
  • You might be missing the definition of a custom scope by the property: spring.security.oauth.client.scope (Okta requires this for client credential flows)

The OAuth2RestTemplate should take care of all of the OAuth complexity for you.

Also, If you are new to SCIM (and not updating an existing SCIM application), take a look at Apache SCIMple!

thanks @bdemers for giving ur suggestion. seems like my url is wrong. thanks again.

1 Like

@marc thanks for following up!!

We are adding some basic URL validation, and other config checks (mostly to prevent typos) in our libs. Can I ask what was wrong with your URL? Maybe it is something we can check for?

hi,
I am getting below exception for similar implementation as marc:

java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:793) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:774) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:335) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at com.example.credsexampleclient.ClientApplication.main(ClientApplication.java:24) [classes/:na]
Caused by: java.lang.NullPointerException: null
at java.lang.StringBuilder.(StringBuilder.java:112) ~[na:1.8.0_151]
at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport.getAccessTokenUri(OAuth2AccessTokenSupport.java:162) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport.retrieveToken(OAuth2AccessTokenSupport.java:137) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider.obtainAccessToken(ClientCredentialsAccessTokenProvider.java:44) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:148) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:121) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.security.oauth2.client.OAuth2RestTemplate.createRequest(OAuth2RestTemplate.java:105) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:725) ~[spring-web-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.security.oauth2.client.OAuth2RestTemplate.doExecute(OAuth2RestTemplate.java:128) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:686) ~[spring-web-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:334) ~[spring-web-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at com.example.credsexampleclient.ClientApplication.run(ClientApplication.java:40) [classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:790) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
… 5 common frames omitted

am able to access below link without issue:
https://myorg.oktapreview.co/oauth2/Default/.well-known/openid-configuration
Please help to check. thanks

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.