简体   繁体   中英

Spring boot Client to invoke REST API secured by OAuth2

I am trying to write a client in spring which would invoke a REST api secured by OAuth2. I have the following which i can use to get a token from Auth Server and then invoke a resource server. Client ID, Client Secret, Username, Password and Access Token URL(URL to fetch the token from), and Resource URL. How do i write a client in spring boot which has above info so i could invoke the resource server URL to fetch my resource or do a POST. After i get the access token which would have a Time To Live in ms(TTL), how do i cache it so i do not have to generate the token for every request. Is it good to cache the token?

You can use declarative rest client - feign spring-cloud-starter-openfeign

for consuming the service and for cacheing the Spring cache to cache the access token.

Tip: call the access token and cache it and resume it in the subsequent calls. Once the endpoint throws unauthroized exception or the token becomes invalid, then the retry mechanism in the feign client can make another call. To implement the retry, you need to have "spring-retry" as one of the dependency.

If you are using JWT tokens, the time-to-live is encoded in the token.

  • You can store it in local storage
  • You can store it as a cookie
  • You can store it in the browser session
  • You can implement an arbitrary way of storing your token

Where you supply your token is up to you. It could be at any stage of communication (request parameter, header, on-demand).

I would suggest to do it like below using CloseableHttpClient

  1. Put details like clientID, user creds, access token in the header of the Http call
  2. Use CloseableHttpClient class -> execute method and pass the header along with URL.
  3. Parse the response and extract the details

  4. Store the retrieved token with either using Spring cache as mentioned by @Sivaraj or you can use a table to store the value along with a timestamp and fetch this value for next calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM