Oauth2Restclient spring example - without springBoot

214 views Asked by At

I am looking for a simple OAuth2restClient example (without SpringBOOT) I am trying with:

    ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
    
    resource.setAccessTokenUri( "https://mypage.com/oauth2/v1/token");
    resource.setClientId("clientid1 ");
    resource.setClientSecret("clientsecret1");
    resource.setGrantType("client_credentials");
     
    resource.setScope(Arrays.asList(new String[] { "openid customscope" }));

    headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.add(" sub1", "");

    
    DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();

    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource, clientContext);
    MyEntity request = new MyEntity();

    
    HttpEntity<MyEntity> request = new HttpEntity<MyEntity>(request, headers);

    ResponseEntity<MyResp> respEntity = null;
    
    ClientCredentialsAccessTokenProvider  prov = new ClientCredentialsAccessTokenProvider();
      
    restTemplate.setAccessTokenProvider(prov);

    respEntity = restTemplate.postForEntity(url, request, MyResp.class);

I always get the "https://mypage.com/oauth2/v1/token" resulted in 401 (Unauthorized); Exception in thread "main" error="access_denied", error_description="Error requesting access token." What is missing, what is the right way, i am passing all the credentials . Any simple working sample please,

1

There are 1 answers

2
Gary Archer On

Your code looks mostly correct but you are using the wrong media type. You should be using Form URL Encoded, as in this HTTP message.

Another possible problem is use of the openid scope, since there is no user identity with this flow. Make sure any scopes you use are configured against the client in the Authorization Server.

LIBRARIES

Out of interest, my personal recommendation is to use respected standards based OAuth libraries provided by security specialists.

As an example, see this client credentials code snippet, which uses connect2id libraries. Benefits are as follows:

  • Clean code with good object names
  • Headers etc are done for you
  • Code works with any provider
  • Good docs, for learning
  • Advanced capabilities, if ever needed

CURL TESTING

I always recommend getting this type of message working with tools first. Try adapting this to your use case and running it from the command line:

curl -u 'myclientid:myclientsecret' \
-X POST http://myauthserver/oauth-token \
-H 'content-type: application/x-www-form-urlencoded' \
-d grant_type=client_credentials \
-d scope=read

If the curl request fails, then analyse the error response details, and also have a look at server logs, so that you understand the cause.