Skip to content

Get access token using Spring Security with a specific use-case

Is this use-case supported for Spring Security 5, or something else, where we don’t have to reinvent the wheel? Thoughts on how to (re)implement this better?

Details are as follows. 3rd party vendor supplied endpoints. We pull info from upstream source then forward to the downstream vendor. Only 2 APIs are required:

  1. Request Access Token
  2. Save Info

Both are actually being called via a gateway. We’ve been given specifics:

(A) The token request requires Basic Auth (standard header – usual base64 encoded). Gateway User and Gateway Password are provided.

Credentials for request token are provided to us:

  • Grant Type = password
  • Consumer Id
  • Consumer Secret
  • Account User
  • Account Password

It responds with an access token and few other details we don’t really care about and of zero value to our use-case.

There is no expires_in info in the response. But I’ve tested it multiple times to know it does expire. Not sure how long right now, I could do more tests to determine that.

(B) The save request requires a different custom header for the same Gateway User / Password, then a Bearer Authorization header in the call to the Save Info API.

Right now, all implementations for above are using RestTemplate. Working fine already. But a token is requested for each save which is costly. Before writing any caching, or some other logic to wait XY minutes before another token request is made, I would appreciate any other options which may already be possibly handled via Spring-specific libraries or further advise on how to handle this scenario.

Apologies if this is not the right place to ask this, or it has already been asked before. Been searching for a similar use-case but can’t seem to find one.




  • Try any one of the option
  1. You can use OAuth2ClientContext which stores your access token.

     final OAuth2RestTemplate restTemplate=new OAuth2RestTemplate(resourceDetails, clientContext);
  2. You can create session & store your token & user details inside it.

     UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user, null,null); 


  • from option 1 Or option 2 you can then fetch existing token for each request at your Filter e.g. PRE_AUTH_FILTER
  • Then check if token expired – if yes request new token Or call refresh token

Check Oauth2 expires_in in below :-