[Vuejs]-Error on auth and cors using Spring Boot, Spring Security and Vue.js with axios

0👍

Cors error usually comes from the backend. It seems like you aren’t specifying which links you want to give access to your backend. In your filterChain() method, the corsConfiguration, add something like
corsConfiguration.setAllowedOrigins(List.of("vueJsSiteLinkHereGoesHere"));

This is the security config I used for my angular project. Note that I did not implement WebMvcConfigurer.

Also, make sure you don’t have @CrossOrigins annotation on your controller class because it will override what is set here.

I’m using jwt for authentication so you might need to add/remove some headers to suit your needs

package com.example.backend.security;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

@EnableWebSecurity
@EnableMethodSecurity()
@Configuration
@RequiredArgsConstructor
public class SecurityConfig {
    private final AppProperties appProps;
    private static final String[] WHITELISTED_URLS = {
            "/auth/**",
    };

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .cors(Customizer.withDefaults()) // by default, use a bean of the name corsConfigurationSource
                .csrf(AbstractHttpConfigurer::disable) // not really needed in REST
                .authorizeHttpRequests((requests) -> requests
                        .requestMatchers(new AntPathRequestMatcher("/h2/**")).permitAll()
                        .requestMatchers(WHITELISTED_URLS).permitAll()
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
                .sessionManagement((session) -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                );
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of(appProps.getFrontendSite()));
        configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"));
        configuration.setAllowedHeaders(List.of("Authorization", "Access-Control-Allow-Origin", "Content-Type",
                "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"));
        configuration.setAllowCredentials(false); // we're using jwt
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

See this video by Dan Vega on youtube. He also has some stuff on vue: https://youtu.be/HRwlT_etr60

0👍

Okay, there are multiple ways for resolve this:

in Backend:
corsConfiguration.setAllowedOriginPatterns(List.of("*"));

Which is the worst….

The second, "workaround"-style is to copy the dist-files into target folder and make a configuration forwarding to index.html.

It’s really crazy, sending rest-requests in a non-browser environment were always successfull, without x-site errors…..

Leave a comment