'Post Request from vue to SpringBoot will be blocked

I am starting to test a little bit with vue.js and spring boot and build a simple login/registration site.

The registration and the login are working fine. I can send a JSON with registration data from vue to spring boot and it will insert the data in a database. After that I can send username and password and I will receive a Bearer Token from spring boot.

So my target is to call a RestEndpoint only if I am logged in/authenticated. I created a simple RestEndpoint:

@CrossOrigin
@RestController
public class HomeController {

    @PostMapping(path = "/api/v1/testendpoint")
    public String getData() {
        return "Data are comming through";
    }
}

And I got the following WebSecurityConfig:

httpSecurity
            .csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests()
                .antMatchers("/api/v1/registration/**")
                .permitAll()
                .antMatchers("/api/v1/login/**")
                .permitAll()
            .anyRequest().authenticated();

    httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
    httpSecurity.headers().cacheControl();

This should send a post request to the testendpoint:

let token = 'abc';

    axios.post("http://localhost:8886/api/v1/testendpoint", {
        headers: {"Authorization": `Bearer ${token}`}
    });

But my request is getting blocked: enter image description here

So as I wanted the WebSecurityConfig like this:

  • registration and login Endpoints are accessable for everyone
  • every other request like "/api/v1/testendpoint" are only available if you are logged in

I thought that I did this with the configuration .authorizeRequests().antMatchers("/api/v1/registration/**").permitAll() .antMatchers("/api/v1/login/**").permitAll() .anyRequest().authenticated();

Can someone tell me what I did wrong?

Cheers, Michael

UPDATE

I forgot to look into the console. There is the following error:

enter image description here

It means that cross-origin is forbidden by external sources. But I enabled it with the Annotation @CrossOrigin in my Controller.

I don't understand this.

Update Found my mistake: I need to add .cors to the WebSecurityConfig. That was all...



Solution 1:[1]

you can disable cors in configuration like csrf disabled. .and().cors().disable()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1