Spring-cloud-gateway security role based authorization: 403 forbidden issue

33 Views Asked by At

Below I am pasting necessary information

I have a spring api gateway project and below demo-controller is inside spring api-gateway project.

@RestController
public class DemoController {

    @GetMapping("/admin/hi")
    public String sayHiFromAdmin(){
        return "hi everyone from admin!";
    }

    @GetMapping("/customer/hi")
    public String sayHiFromCustomer(){
        return "hi everyone from customer!";
    }

}

SecurityConfig

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity serverHttpSecurity) {
        return serverHttpSecurity.csrf(ServerHttpSecurity.CsrfSpec::disable)
                .authorizeExchange(authorizeExchangeSpec -> authorizeExchangeSpec
                        .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                        .pathMatchers("/auth/**").permitAll()
                        .pathMatchers("/admin/**").hasAuthority("ROLE_admin")
                        .pathMatchers("/customer/**").hasAnyAuthority("ROLE_admin", "ROLE_customer")
                        .anyExchange().authenticated()
                ).oauth2ResourceServer(
                        oAuth2ResourceServerSpec -> oAuth2ResourceServerSpec.jwt(Customizer.withDefaults())
                )
                .build();
    }

}

we have 3 client level roles in keycloack which are admin, tenant, customer and three users admin_user, customer_user, tenant_user.

admin_user, customer_user, tenant_user have admin, customer and tenant roles respectively.

My auth api is working fine with any one of the user names and i am able to generate token as well, roles can be seen in parsed token as well which means roles are properly mapped with usernames.

now the problem is when i am trying to hit that "admin/hi" endpoint using admin_user username it is giving me 403 forbidden, same with "customer/hi" endpoint using customer_user.

I've tried using both hasRole and hasAuthority and tried adding prefix "ROLE_" and without prefix also with both hasAuthority and hasRole but the issue persists. I beleive keycloak configuration is also fine because I am able to generate token.

Any insights or suggestions would be greatly appreciated. Thank you!

0

There are 0 best solutions below