Spring security – OAuth2RestTemplate

If we use Spring OAuth2RestTemplate it automatically sets the “Authorization” header with “Bearer <<token>>” value. It also takes care of fetching the new token if the token expires. Very useful.

/**
* Acquire or renew an access token for the current context if necessary. This method will be called automatically
* when a request is executed (and the result is cached), but can also be called as a standalone method to
* pre-populate the token.
*
* @return an access token
*/
public OAuth2AccessToken getAccessToken() throws UserRedirectRequiredException {

OAuth2AccessToken accessToken = context.getAccessToken();

if (accessToken == null || hasTokenExpired(accessToken)) {
try {
accessToken = acquireAccessToken(context);
}
catch (UserRedirectRequiredException e) {
context.setAccessToken(null); // No point hanging onto it now
accessToken = null;
String stateKey = e.getStateKey();
if (stateKey != null) {
Object stateToPreserve = e.getStateToPreserve();
if (stateToPreserve == null) {
stateToPreserve = “NONE”;
}
context.setPreservedState(stateKey, stateToPreserve);
}
throw e;
}
}
return accessToken;
}

private boolean hasTokenExpired(OAuth2AccessToken accessToken) {
Calendar now = Calendar.getInstance();
Calendar expiresAt = (Calendar) now.clone();
if (accessToken.getExpiration() != null) {
expiresAt.setTime(accessToken.getExpiration());
expiresAt.add(Calendar.SECOND, -this.clockSkew);
}
return now.after(expiresAt);
}

%d bloggers like this: