Spring Boot OAuth2: How to retrieve user token info details

Refresh

December 2018

Views

5.2k time

3

I'm following https://spring.io/guides/tutorials/spring-boot-oauth2/ and everything works so far. I actually even managed to hook up also Google Oauth as a second Auth provider. Now I'm trying to read out the infos from the token info endpoint in my backend to sync it with my local DB and adjust the ouput. But i'm somehow struggling to retrieve the information.

The tutorial creates at some point this endpoint:

@RequestMapping("/user")
public Principal user(Principal principal) {
    return principal;
}

when called, this is displaying (after successfull login) correctly for me

{
    "authorities": [...],
    "details": {...},
    "authenticated": true,
    "userAuthentication": {
        "authorities": [...],
        "details": {
            "email": "[email protected]",
            "name": "Foo Bar",
            "id": "12345674890000"
        },
        "authenticated": true,
        "principal": "12345674890000",
        "credentials": "N/A",
        "name": "12345674890000"
    },
    "oauth2Request": {},
    "clientOnly": false,
    "credentials": "",
    "principal": "12345674890000",
    "name": "12345674890000"
}

so somehow spring boot security is picking up the right information. Now I'm trying to build an Interceptor (basic functionality is working, the interceptor is called on every request) to handle this information. I'm struggling to get e.g. the email adress now. I found this answer, but its referring to an old version of spring boot, and just links to a new Interface, but I'm wondering if I need that (It also looks very complicated for the simple usecase i think i have). What would be the best approach to get the information from this /user endpoint in my spring app without actually calling my own endpoint to retrieve it?

the only thing i managed to pick up was via the SecurityContextHolder the principle id and other stuff which did not help me. i did not actualyl retrieve e.g. the email address.

1 answers

2

Попробуйте использовать SecurityContext:

SecurityContextHolder.getContext().getAuthentication().getPrincipal();

Он будет представлен реальный объект пользователя, который в настоящее время LoggedIn