Spring Cloud Gateway — Resource Server with Keycloak RBAC

Introduction

@RestController
public class Controller {

@GetMapping("/product")
@RolesAllowed({"product_read"})
public String getProduct(Principal principal) {
return "Response from Product Service, User Id:" + principal.getName();
}
}
spring:
security:
oauth2:
resourceserver:
jwt:
jwk-set-uri: http://localhost:8080/auth/realms/My-Realm/protocol/openid-connect/certs

server:
port: 9191
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2ResourceServer()
.jwt(jwt -> jwt.jwtAuthenticationConverter( jwtAuthenticationConverter()));
}

private Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter() {
JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
jwtConverter.setJwtGrantedAuthoritiesConverter(new RealmRoleConverter());
return jwtConverter;
}
}
public class RealmRoleConverter implements Converter<Jwt, Collection<GrantedAuthority>> {
@Override
public Collection<GrantedAuthority> convert(Jwt jwt) {
final Map<String, List<String>> realmAccess = (Map<String, List<String>>) jwt.getClaims().get("realm_access");
return realmAccess.get("roles").stream()
.map(roleName -> "ROLE_" + roleName)
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}
}

Connecting Resource Server to API Gateway

spring:
cloud:
gateway:
default-filters:
- TokenRelay
routes:
- id: product-resource-service
uri: http://localhost:9191
predicates:
- Path=/product/**
java -jar target/spring-cloud-gateway-keycloak-oauth2-0.0.1-SNAPSHOT.jarjava -jar target/product-service-0.0.1-SNAPSHOT.jar

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store