I have an api which uses AD Token for authorization. I am trying to fetch the username of the user inside my service component. But im failing to. I have tried this.
val authentication: Authentication = SecurityContextHolder.getContext().authentication
println(authentication.name) // Random short string with 3 "-". Not JWT
println(authentication.details.toString()) // WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null]
println(authentication.authorities.toString()) // Prints Scope [SCOPE_User.Read]
println(authentication.principal) // org.springframework.security.oauth2.jwt.Jwt@xxxxxxxx
The token is from AD and it does contain userdata. The payload contains these fields with user related stuff. I removed the rest.
{,
"family_name": "Wick",
"given_name": "John",
"name": "WickJohn",
"roles": [
"User"
],
"scp": "User.Read",
"unique_name": "[email protected]",
"upn": "[email protected]",,
}
Anyone have any idea?
CodePudding user response:
To get username/user info in Spring OAuth2 Resource Server, please try the below:
- Make sure to configure
resource server
in theAuthorization Server
too. - To get user info by token,
resource server
provides a filterOAuth2AuthenticationProcessingFilter
- The generated token is set into
SecurityContextHolder
. - Otherwise, When accessing userinfo try including the access token in the header (Authorization Bearer).
If the above doesn't work, then try using On Behalf Of Flow
and the code mentioned in this GitHub blog.
For more information, please refer below links:
Azure AD 2.0 Troubleshooting – OAuth Architecture Guidance (authguidance.com)
How to get userinfo by jwt token in spring security oauth2 authorization server? - Stack Overflow
CodePudding user response:
I solved it easily just reading the jwt manually.
val authentication = SecurityContextHolder.getContext().authentication
val jwt = authentication.principal as Jwt
println(jwt.claims["name"])
Still would be interesting to find out why i didnt get it automatically