-2

I have a CORS problem. I am using spring boot and vue to make a fullstack web. But I get the CORS error when I make the request from the front with axios to the Spring Security form. I'm sure I have to do something in my Authorization class to make the request, but I don't know.

Here is my code:

@EnableWebSecurity
@Configuration
public class WebAuthorization {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http.formLogin()
                .usernameParameter("email")
                .passwordParameter("password")
                .loginPage("/api/login");

        http.logout().logoutUrl("/api/logout").deleteCookies("JSESSIONID");

        return http.build();
    }

I hope you can make the request from the front with Vue to the form that I have with spring security.

  • 1
    You've to enable CORS in your backend and add the domains that your app would accept. This could be achieved with a WebConfig class in Spring. – Lucas David Ferrero Jan 10 '23 at 19:44
  • 2
    duplicate [How to configure CORS in a Spring Boot + Spring Security application?](https://stackoverflow.com/questions/36968963/how-to-configure-cors-in-a-spring-boot-spring-security-application) – Toerktumlare Jan 11 '23 at 06:58

1 Answers1

0

You can configure CORS using CorsConfigurationSource Bean. For example:

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
    configuration.setAllowedMethods(Arrays.asList("GET","POST"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

In case you want to allow cross origin requests:

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.applyPermitDefaultValues();
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

See Spring Security documentation for more information.

  • Hello Arturas, thank you for your answer, but the error continue. I don't know, the code that you pass me, i put inside on my class WebAuthorization? Here is my request in Vue: axios({ method:'post', url:'http://localhost:8080/api/login', params:{ email: this.email, password: this.password }, config: { headers: {'Content-Type': 'application/x-www-form-urlencoded'}} }) – Sebastián valbuena Jan 11 '23 at 01:27