Search code examples
spring-bootvue.jsoauthkeycloak

Keycloak + SPA as client (Vue) + Spring Cloud Gateway as resource server + Spring Boot Microservices


I want my project to work like this:

enter image description here

Everything fine except for Vue(axios) returns 401 error when I request some data from microservice through gateway.

Authorization token with 'Bearer' is set for each axios request, with exacly same token I can get data using Postman. Also its work if I move

<dependency>
 <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

and

security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://localhost:8900/realms/SomeRealm

from Spring gateway to microservice.

But I want only gateway to approve token and microservice should not know anything about it or keycloak.

Vue 2, Spring boot 2.17, Java 11, Keycloak 22


Solution

  • Ok I did it. The problem was with a preflight OPTIONS header, which didn't include token. Solved with SecurityWebFilterChain:

    @Bean
    public SecurityWebFilterChain securityFilterChain(ServerHttpSecurity http) throws Exception {
        http
                .authorizeExchange()
                .pathMatchers(HttpMethod.OPTIONS).permitAll() // Allow OPTIONS requests without authentication
                .anyExchange().authenticated()
                .and()
                .oauth2ResourceServer()
                .jwt();
        return http.build();
    }