0

I use keycloak with Spring Boot api rest, but I get this error:

Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"

I believe this token is valid.

Code:

    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        
        System.out.println("Entro a seguridad");
        http.authorizeHttpRequests()
            .requestMatchers("/all/**")
            .hasAnyRole("user_roles")
            .anyRequest()
            .permitAll();
        http.oauth2Login()
            .and()
            .logout()
            .addLogoutHandler((LogoutHandler) keycloakLogoutHandler)
            .logoutSuccessUrl("/");
        http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        return http.build();

jwt

I expect the token works. How do I fix this error?

Binoy Babu
  • 16,699
  • 17
  • 91
  • 134
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Apr 23 '23 at 15:37
  • I have the same problem during tests using REST-assured + Testcontainers + Keycloak. I receive `WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"` Only one difference I can see between real JWT token and token generated by testcontainers-keycloak is order in field `scope`. The real valid token has value `"email profile"` during in test this has `"profile email"` – TOUDIdel Jul 21 '23 at 08:35

1 Answers1

1

Apparently, you have not configured an authentication converter, which means the spring authorities are mapped from the scope claim with SCOPE_ prefix (and not Keycloak private claims with ROLE_ prefix which is required by hasRole).

What you need is change your resource-server configuration to http.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(...)) and provide an authentication converter mapping authorities from realm_access.roles (adding ROLE_ prefix), and then build a JwtAuthenticationToken from it. Samples in this answer and those tutorials I wrote (and my bet is you should read the introduction README).

ch4mp
  • 6,622
  • 6
  • 29
  • 49