Search code examples
javaspringsecurityoauth-2.0keycloak

Keycloak + Spring 3


How I can enable **bearer-only ** mode for auth? Now when my request have no token app redirect me to KeyCloak login page but I want to get 403 forbidden.

SecurityFilterChain

@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
    http.oauth2Login()
            .and()
            .csrf().disable();

    http.oauth2ResourceServer().jwt();
    http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.ALWAYS);

    http
            .authorizeHttpRequests()
            .requestMatchers("/test").permitAll()
            .anyRequest().authenticated();

    return http.build();
}

application.yml

spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: paper_java
            client-secret: JEEcO8mJhKzkcx2aZ2sgZ8E2JsSx4Lms
            scope: openid
            authorization-grant-type: authorization_code
        provider:
          keycloak:
            issuer-uri: http://localhost:9999/realms/ss
            user-name-attribute: preferred_username
      resourceserver:
        jwt:
          issuer-uri: http://localhost:9999/realms/ss

Im trying to make keycloak only checking token validation service, but got login page.


Solution

  • You "login" to an OAuth2 client (with authorization_code flow), not to an OAuth2 resource server and requests to an OAuth2 client from a browser are authorized with sessions, not Bearer tokens in authorization header. Before trying to configure your app as a resource server (and use tokens security), you should be sure that you can actually send tokens from what you are trying to consume it with (browsers are very bad candidates for that).

    Also, you should not mix oauth2Login and oauth2ResourceServer in the same filter chain, the security is too different:

    • oauth2Login is based on sessions, requires CSRF protection (disabling it like you do is a mistake), and unauthorized requests to secured routes should probably be redirected to login (302 status)
    • oauth2ResourceServer can (should?) be configured stateless (without session), is not exposed to CSRF attacks and unauthorized requests to secured routes should probably be answered 401 Unauthorized.

    I suggest that you have a look at my OAuth2 essentials and tutorials.