Skip to content

Commit 808b8c3

Browse files
olivier.antoinejzheaux
authored andcommitted
Avoid ClassCastException if principalClaim value is not a String
Closes gh-9212
1 parent fe93326 commit 808b8c3

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverter.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
* @author Rob Winch
3030
* @author Josh Cummings
3131
* @author Evgeniy Cheban
32+
* @author Olivier Antoine
3233
* @since 5.1
3334
*/
3435
public class JwtAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
@@ -43,8 +44,8 @@ public final AbstractAuthenticationToken convert(Jwt jwt) {
4344
if (this.principalClaimName == null) {
4445
return new JwtAuthenticationToken(jwt, authorities);
4546
}
46-
String name = jwt.getClaim(this.principalClaimName);
47-
return new JwtAuthenticationToken(jwt, authorities, name);
47+
String principalClaimValue = jwt.getClaimAsString(this.principalClaimName);
48+
return new JwtAuthenticationToken(jwt, authorities, principalClaimValue);
4849
}
4950

5051
/**

oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverterTests.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
*
3737
* @author Josh Cummings
3838
* @author Evgeniy Cheban
39+
* @author Olivier Antoine
3940
*/
4041
public class JwtAuthenticationConverterTests {
4142

@@ -103,4 +104,12 @@ public void convertWhenPrincipalClaimNameSet() {
103104
assertThat(authentication.getName()).isEqualTo("100");
104105
}
105106

107+
@Test
108+
public void convertWhenPrincipalClaimNameSetAndClaimValueIsNotString() {
109+
this.jwtAuthenticationConverter.setPrincipalClaimName("user_id");
110+
Jwt jwt = TestJwts.jwt().claim("user_id", 100).build();
111+
AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt);
112+
assertThat(authentication.getName()).isEqualTo("100");
113+
}
114+
106115
}

0 commit comments

Comments
 (0)