1

I am using Spring 5 Oauth2. I can see current valid tokens.

Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByClientId("clientIdPassword");
    if (tokens != null) {
        for (OAuth2AccessToken token : tokens) {
            tokenValues.add(token.getValue());
        }
    }

Above code block shows me valid tokens whose client id is clientIdPassword, but I want to get only current logged user object. I tried Authentication authentication = SecurityContextHolder.getContext().getAuthentication();but it returns anonymous user. Is there a way to get the only current logged user object?

Eniss
  • 975
  • 2
  • 20
  • 40

2 Answers2

1

In your Token Service, you can add the OAuth2Authentication Class as an argument

 @RequestMapping(method = RequestMethod.POST, value = "/oauth/token/revokeById/{tokenId}")
    @ResponseBody
    public void revokeToken(HttpServletRequest request, @PathVariable String tokenId,OAuth2Authentication auth) {

Springboot will automatically map the logged-in user details to this object. Now, you can do the following to access the username

auth.getPrincipal().toString()
CGS
  • 2,782
  • 18
  • 25
  • `OAuth2Authentication` returns null interestingly... But I do see the token from `tokenStore.findTokensByClientId("clientIdPassword");`. – Eniss Mar 09 '18 at 07:11
  • @Chids Any idea on this issue https://stackoverflow.com/questions/49229551/spring-oauth2-0-getting-user-roles-based-on-client-id – Alex Man Mar 12 '18 at 08:32
  • @eniss are you doing this logic in your authorization server and are you using jdbc token store? – CGS Mar 12 '18 at 14:05
0

Usually, your code is the right way to get current login user object.
If you want to find other ways refer here : http://www.baeldung.com/get-user-in-spring-security

Min Hyoung Hong
  • 1,102
  • 9
  • 13