import com.hazelcast.core.IMap; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
private Map handleRefreshToken(HttpServerExchange exchange, String refreshToken, String scope, Map formMap) throws ApiException {
if(logger.isDebugEnabled()) logger.debug("refreshToken = " + refreshToken + " scope = " + scope);
Client client = authenticateClient(exchange, formMap);
if(client != null) {
// make sure that the refresh token can be found and client_id matches.
IMap tokens = CacheStartupHookProvider.hz.getMap("tokens");
RefreshToken token = tokens.remove(refreshToken);
if(token != null) {
String userId = token.getUserId();
String clientId = token.getClientId();
String oldScope = token.getScope();
if(client.getClientId().equals(clientId)) {
IMap users = CacheStartupHookProvider.hz.getMap("users");
User user = users.get(userId);
if(scope == null) {
scope = oldScope; // use the previous scope when access token is generated
} else {
// make sure scope is the same as oldScope or contained in oldScope.
if(!matchScope(scope, oldScope)) {
throw new ApiException(new Status(MISMATCH_SCOPE, scope, oldScope));
}
}
String jwt;
try {
jwt = JwtHelper.getJwt(mockAcClaims(client.getClientId(), scope, userId, user.getUserType().toString(), null));
} catch (Exception e) {
throw new ApiException(new Status(GENERIC_EXCEPTION, e.getMessage()));
}
// generate a new refresh token and associate it with userId and clientId
String newRefreshToken = UUID.randomUUID().toString();
RefreshToken newToken = new RefreshToken();
newToken.setRefreshToken(newRefreshToken);
newToken.setUserId(userId);
newToken.setClientId(client.getClientId());
newToken.setScope(scope);
tokens.put(refreshToken, newToken);
Map resMap = new HashMap<>();
resMap.put("access_token", jwt);
resMap.put("token_type", "bearer");
resMap.put("expires_in", config.getExpiredInMinutes()*60);
resMap.put("refresh_token", newRefreshToken);
return resMap;
} else {
// mismatched client id
throw new ApiException(new Status(MISMATCH_CLIENT_ID, client.getClientId(), clientId));
}
} else {
// refresh token cannot be found.
throw new ApiException(new Status(REFRESH_TOKEN_NOT_FOUND, refreshToken));
}
}
return new HashMap<>(); // return an empty hash map. this is actually not reachable at all.
}