I am testing a method that override some parameter in jwtGrantedAuthoritiesConverter but always when i debug get that this collection (Collection authorities = jwtGrantedAuthoritiesConverter.convert(jwt);) is empty did not know the reason !! here is my code
can some one help me please .. Thank you!
class SecurityConfigTest {
@Test
void convertWithOverriddenGrantedAuthoritiesConverter() {
Jwt jwt = this.jwt(Collections.singletonMap("scope", "message:read message:write"));
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthorityPrefix("");
jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles");
Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt);
assertThat(authorities).containsExactly(
new SimpleGrantedAuthority("message:read"),
new SimpleGrantedAuthority("message:write"));
Assert.assertTrue(authorities.contains("roles"));
}
private Jwt jwt(Map<String, Object> claims) {
Map<String, Object> headers = new HashMap<>();
headers.put("alg", JwsAlgorithms.RS256);
return new Jwt("token", Instant.now(), Instant.now().plusSeconds(3600), headers, claims);
}
}
according to the docs the default claim that spring will use when trying to find Authorities to mapping scopes to roles is the scope
claim in the JWT.
You can override this behavior by supplying a custom JwtGrantedAuthoritiesConverter
and use the setAuthoritiesClaimName
to set a different claim.
the above code has this line
jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles");
so spring tries to find a claim called roles
in the JWT, that it can map to authorities and it can't find it, so it returns empty.
Removing that line will fix the problem.