Currently I've got Oauth2 through Cognito set up for my Spring API. I mostly followed this resource and authentication is working so far.
To be able to access a private user's profiles and edit them I want to be able to compare the currently authenticated user with the relevant user of the profile to determine if they're authorized.
My thought on how to do this is that I would define a custom PreAuthorize type that would compare the User from the database's email with the authenticated user's email using the SecurityContextHolder.
However, I'm not able to get the email from the Cognito token. Debugging an endpoint with the below method
var principal = (Jwt)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
principal.getClaims().forEach((k, v) -> System.out.println(k + ": " + v));
None of the values correspond to email. The User Pool is using email to log in, but it creates a generated uid for the username and that's what I receive here.
I could hit the userinfo endpoint manually to try and get the email, but that seems like the wrong way to go about it. Is there a way I can get the user's email to be included in the access token instead of the username? Is there a better way to compare Cognito data to database data?
Here's my relevant code, fairly simple for now:
WebSecurityConfigurerAdapter -
@Override
public void configure(HttpSecurity http) throws Exception {
http.cors();
http.csrf().disable();
http.authorizeRequests(expressionInterceptUrlRegistry -> expressionInterceptUrlRegistry.anyRequest().authenticated())
.oauth2ResourceServer().jwt();
}
Application.yaml -
security:
oauth2:
resourceserver:
jwt:
issuer_uri: https://cognito-idp.us-east-1.amazonaws.com/us-east-1_pKhoaGXXu