Java Get access token using Client Credentials grant and store the token

Viewed 2486

I am bit lost here and need some direct please. I am new to Java and this is the first program that i am trying to write and obviously struggling with it for a month or so. So currently we use postman to input client ID/secret to get access token from a 3rd party API, using which we can request resources from another end point of this 3rd party. I am trying reference multiple resources like this spring security example https://github.com/spring-projects/spring-security/blob/master/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager.java

https://www.baeldung.com/spring-webclient-oauth2#5-security-web-filter-chain

https://mkyong.com/java/how-to-send-http-request-getpost-in-java/

and few more in stackoverflow as well.. but when i try and recreate those examples for me, it doesn't work and i am failing and kind off gave up actually...

in the Application.yml file, this is the configuration that i have.


spring: security: oauth2: client: authorization-grant-type: client_credentials client-id: client-secret: token-uri: "url here"

Please can someone give me some directions on how i can create a Java/spring code to get this token. the credentials will have to go in the header of http request.

1 Answers

I'd recommend the Connect2ID libraries, since they are very well documented, implemented by experts and developer friendly:

If you're using Intellij you just need to reference libraries like this in your maven pom.xml file and maven will download the library for you:

<dependency>
  <groupId>com.nimbusds</groupId>
  <artifactId>oauth2-oidc-sdk</artifactId>
  <version>8.4</version>
</dependency>

It is usual to manage token storage as follows in this flow:

  • Just store the access token in memory
  • Eventually the access token will expire and you will get a 401 response
  • When this happens, just authenticate again to get a new token ...
  • ... and retry the API call with the new access token
Related