Bad, good or best practice?
Context: Spring boot + Keycloak + Permission based on authorization scope + Spring security
Requirement: Secure an API, MyService, developed with Spring boot and RestController. The client provides an authentication JWT
Details:
Keycloak:
Spring Boot (MyService):
pom.xml
application.yml
spring.security.oauth2.resourceserver.jwt.jwk-set-uri = http://localhost:8080/realms/myrealm/protocol/openid-connect/certs
Parts of java controller class StatusController (@RestController, @RequestMapping("/users"))
Spring security layer configuration
...
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(new KeycloakScopeConverter());
http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()).
oauth2ResourceServer( oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter))
);
return http.build();
}
KeycloakScopeConverter, a java class that, given the incoming JWT (the one provided by the front end), obtains an RPT token and extracts the authorization scopes from this.
makes an http POST with
url: http://localhost:8080/realms/myrealm/protocol/openid-connect/token
grant_type: urn:ietf:params:oauth:grant-type:uma-ticket
audience: client_service
header: "Authorization", " Bearer " + jwt.getTokenValue()) (jwt fornito dal FE)
The scopes are extracted from the array permissions:
ArrayList _scopes = new ArrayList<>();
for (Map permission : permissions) {
ArrayList scopes = (ArrayList) permission.get(“scopes”);
if (scopes != null) {
for (String scope : scopes) {
_scopes.add(scope);
}
}
}
Collection returnValue = scopes.stream().map(scope -> “SCOPE“ + scope).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
In this way a control using the @PreAuthorize("hasAuthority("..."))
The question is: Is this a bad, good or best practice?
Over to you.
--
You received this message because you are subscribed to the Google Groups "Keycloak User" group.
To unsubscribe from this group and stop receiving emails from it, send an email to keycloak-use...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/keycloak-user/fd3b207c-1090-42f5-93a3-5e9e192821b5n%40googlegroups.com.