Reputation: 129
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 ?
Upvotes: 1
Views: 1722
Reputation: 29
I would suggest to do it like below using CloseableHttpClient
Parse the response and extract the details
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.
Upvotes: 1
Reputation: 688
If you are using JWT tokens, the time-to-live is encoded in the token.
Where you supply your token is up to you. It could be at any stage of communication (request parameter, header, on-demand).
Upvotes: 1
Reputation: 187
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.
Upvotes: 2