*/
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) throws AuthenticationException, InvalidTokenException {
// read and load up the existing token
String incomingTokenValue = tokenRequest.getRequestParameters().get("token");
OAuth2AccessTokenEntity incomingToken = tokenServices.readAccessToken(incomingTokenValue);
// check for scoping in the request, can't up-scope with a chained request
Set<String> approvedScopes = incomingToken.getScope();
Set<String> requestedScopes = tokenRequest.getScope();
if (requestedScopes == null) {
requestedScopes = new HashSet<String>();
}
// do a check on the requested scopes -- if they exactly match the client scopes, they were probably shadowed by the token granter
if (client.getScope().equals(requestedScopes)) {
requestedScopes = new HashSet<String>();
}
// if our scopes are a valid subset of what's allowed, we can continue
if (approvedScopes.containsAll(requestedScopes)) {
if (requestedScopes.isEmpty()) {
// if there are no scopes, inherit the original scopes from the token
tokenRequest.setScope(approvedScopes);
} else {
// if scopes were asked for, give only the subset of scopes requested
// this allows safe downscoping
tokenRequest.setScope(Sets.intersection(requestedScopes, approvedScopes));
}
// NOTE: don't revoke the existing access token
// create a new access token
OAuth2Authentication authentication = new OAuth2Authentication(getRequestFactory().createOAuth2Request(client, tokenRequest), incomingToken.getAuthenticationHolder().getAuthentication().getUserAuthentication());
return authentication;
} else {
throw new InvalidScopeException("Invalid scope requested in chained request", approvedScopes);