how do I get realm information from Authentication object ? #218
-
how can I get realm information from the Authentication object? I cannot see it in any field or the jwt claims Before switching to springboot3 , we were working with keycloak-starter and the authentication was casted to KeycloakAuthenticationToken where there was a keycloakDeployment object, which was holding realm information |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You can infer it from the If you want to add some helper methods to the
@Configuration
@EnableMethodSecurity()
public class SecurityConfig {
@Data
@EqualsAndHashCode(callSuper = true)
public static class KommradAuthentication extends OAuthentication<OpenidClaimSet> {
private static final Pattern REALM_PATTERN = Pattern.compile("^.*/realms/([^/]+).*$");
private final String tenant;
public KommradAuthentication(OpenidClaimSet claims,
Collection<? extends GrantedAuthority> authorities, String tokenString) {
super(claims, authorities, tokenString);
this.tenant = REALM_PATTERN.matcher(claims.getIssuer().toString()).group(1);
}
}
@Bean
JwtAbstractAuthenticationTokenConverter authenticationFactory(
Converter<Map<String, Object>, Collection<? extends GrantedAuthority>> authoritiesConverter,
OpenidProviderPropertiesResolver addonsPropertiesResolver) {
return jwt -> {
final var opProperties = addonsPropertiesResolver.resolve(jwt.getClaims())
.orElseThrow(() -> new NotAConfiguredOpenidProviderException(jwt.getClaims()));
final var claims = new OpenidClaimSet(jwt.getClaims(), opProperties.getUsernameClaim());
return new KommradAuthentication(claims, authoritiesConverter.convert(claims),
jwt.getTokenValue());
};
}
} Default |
Beta Was this translation helpful? Give feedback.
You can infer it from the
issuer
claim with a regex like^.*/realms/([^/]+).*$
.If you want to add some helper methods to the
Authentication
instance in the security context (likeKeycloakAuthenticationToken
was doing):Authentication
implementation (you might useAbstractAuthenticationToken
,JwtAuthenticationToken
, or this lib'sOAuthentication
as base class)JwtAbstractAuthenticationTokenConverter
bean in your conf (something that can turn aJwt
into something extendingAbstractAuthenticationToken
)