Why Spring Security authentication causes CORS error

Why Spring Security authentication causes CORS error

I have a backend server made in Java with Spring Boot, Security and Web and a client made with Angular.

I have a backend server made in Java with Spring Boot, Security and Web and a client made with Angular.

Currently I am trying to make a simple request under localhost:8080/resource.

The controller for this address is shown bellow:

@RestController
public class IndexController {
    @CrossOrigin
    @RequestMapping("/resource")
    public Map<String, Object> home() {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");

    return model;
}

}

And the Angular client (the part that performs the request) is this:

import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";

@Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent { public title = "Security Client"; public greeting = {};

constructor(private http: HttpClient) {
    http.get("http://localhost:8080/resource").subscribe(data =&gt; this.greeting = data);
}

}

The problem by using just what was shown is that I get a CORS error.

Whether removing Spring Security from my pom.xml or adding this configuration:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests().antMatchers("/resource").permitAll();
}

}

Solves the problem.

What I wanna know is why I am getting an CORS error instead of a 401 Unauthorized when accessing an address that demands user authentication.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Spring Boot Tutorials - Spring Boot Full Course

Spring Boot Tutorials | Full Course - What is Spring? Spring Boot is an open source Java-based framework used to create a Micro Service. Spring Boot contains a comprehensive infrastructure support for developing a micro service and enables you to develop enterprise-ready applications that you can “just run”.

Java Spring - Limiting Query Result with Spring Data JPA

Java Spring - Limiting Query Result with Spring Data JPA

Full-stack Reactive Java with Spring Framework, Spring Boot and Project Reactor

Reactive programming offers Java developers a way to build message-driven, elastic, resilient, and responsive services...yet many Java developers don't know where to begin.