oauth-2.0microservicesjhipsteraccess-tokencloudfoundry-uaa

Fetch Current Access Token in JHipster UAA based Microservice Applications


I have a JHipster Microservices having UAA based authentication (OAuth 2.0). I have set certain claims in token through IatTokenEnhancer. I want to use the value of these claims in each request. How can I fetch the access token from current request?


Solution

  • Token is accessible via SecurityContext. Following is the code:

    public static Optional<String> getCurrentUserToken() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(securityContext.getAuthentication())
            .filter(authentication -> authentication.getDetails() instanceof OAuth2AuthenticationDetails)
            .map(authentication -> ((OAuth2AuthenticationDetails) authentication.getDetails()).getTokenValue());
    }