spring-security

Spring Security: Get OAuth2AccessToken additional information in my controller class


Hi have a situation where I need the additional details I stored with my OAuth2AccessToken to be retrieved in my controller class. I have used

accessToken.setAdditionalInformation(additionalInformation);

to save the data. How can I get the data I stored in additionalInformation in my controller class?


Solution

  • We can do with HttpServletRequest, by getting the token from the Authorization header and then get the token details from the token store. The snippet for my code is shared below.

    public TokenData getTokenData(HttpServletRequest request) throws InputInvalidException {
        TokenData tokenData = null;
        try {
            String authHeader = request.getHeader("Authorization");
            if (authHeader != null) {
                String tokenValue = authHeader.toLowerCase().replace("bearer", "").trim();
                OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
                tokenData = (TokenData) accessToken.getAdditionalInformation().get("tokenData");
            }
        } catch (Throwable exception) {
            logger.error(exception);
            throw new InputInvalidException("token invalid");   
        }
        return tokenData;
    }