Avoid ClassCastException if principalClaim value is not a String

Closes gh-9212
This commit is contained in:
olivier.antoine 2020-11-23 21:05:32 +01:00 committed by Josh Cummings
parent fe93326087
commit 808b8c3256
2 changed files with 12 additions and 2 deletions

View File

@ -29,6 +29,7 @@ import org.springframework.util.Assert;
* @author Rob Winch
* @author Josh Cummings
* @author Evgeniy Cheban
* @author Olivier Antoine
* @since 5.1
*/
public class JwtAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
@ -43,8 +44,8 @@ public class JwtAuthenticationConverter implements Converter<Jwt, AbstractAuthen
if (this.principalClaimName == null) {
return new JwtAuthenticationToken(jwt, authorities);
}
String name = jwt.getClaim(this.principalClaimName);
return new JwtAuthenticationToken(jwt, authorities, name);
String principalClaimValue = jwt.getClaimAsString(this.principalClaimName);
return new JwtAuthenticationToken(jwt, authorities, principalClaimValue);
}
/**

View File

@ -36,6 +36,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Josh Cummings
* @author Evgeniy Cheban
* @author Olivier Antoine
*/
public class JwtAuthenticationConverterTests {
@ -103,4 +104,12 @@ public class JwtAuthenticationConverterTests {
assertThat(authentication.getName()).isEqualTo("100");
}
@Test
public void convertWhenPrincipalClaimNameSetAndClaimValueIsNotString() {
this.jwtAuthenticationConverter.setPrincipalClaimName("user_id");
Jwt jwt = TestJwts.jwt().claim("user_id", 100).build();
AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt);
assertThat(authentication.getName()).isEqualTo("100");
}
}