diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverter.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverter.java index 22fea53fb0..e7199d8dc9 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverter.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverter.java @@ -22,21 +22,30 @@ import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtClaimNames; import org.springframework.util.Assert; /** * @author Rob Winch * @author Josh Cummings + * @author Evgeniy Cheban * @since 5.1 */ public class JwtAuthenticationConverter implements Converter { private Converter> jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); + private String principalClaimName; + @Override public final AbstractAuthenticationToken convert(Jwt jwt) { Collection authorities = extractAuthorities(jwt); - return new JwtAuthenticationToken(jwt, authorities); + if (this.principalClaimName == null) { + return new JwtAuthenticationToken(jwt, authorities); + } + + String name = jwt.getClaim(this.principalClaimName); + return new JwtAuthenticationToken(jwt, authorities, name); } /** @@ -65,4 +74,16 @@ public class JwtAuthenticationConverter implements Converter this.jwtAuthenticationConverter.setPrincipalClaimName(null)) + .withMessage("principalClaimName cannot be empty"); + } + + @Test + public void whenSettingEmptyPrincipalClaimName() { + assertThatIllegalArgumentException() + .isThrownBy(() -> this.jwtAuthenticationConverter.setPrincipalClaimName("")) + .withMessage("principalClaimName cannot be empty"); + } + + @Test + public void whenSettingBlankPrincipalClaimName() { + assertThatIllegalArgumentException() + .isThrownBy(() -> this.jwtAuthenticationConverter.setPrincipalClaimName(" ")) + .withMessage("principalClaimName cannot be empty"); + } + + @Test + public void convertWhenPrincipalClaimNameSet() { + this.jwtAuthenticationConverter.setPrincipalClaimName("user_id"); + + Jwt jwt = jwt().claim("user_id", "100").build(); + AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt); + + assertThat(authentication.getName()).isEqualTo("100"); + } }