0
votes

"Access to XMLHttpRequest at 'http://localhost:8080' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."

This is the error I get when i try to login through basic authentication in spring security. @CrossOrigin() annotation is included in rest controller. But still i get this message. I've also tried @CrossOrigin(origins = { "localhost:4200"}, allowedHeaders={"Accept"}), still the message is shown whenever i try to login.

Angular method to authenticate:(I'm returning the logged in user id in rest controller)

authenticate(username, password) {
  const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(username + ':' + password) });

  return this.http.get<number>('http://localhost:8080/hiring-prediction-tool/users/login', {headers})
  .pipe(map(
      userData => {
        console.log(userData, 'userData');
        sessionStorage.setItem('username',username);
        let authString = 'Basic ' + btoa(username + ':' + password);
        sessionStorage.setItem('basicauth', authString);
        return userData;
      }
    )
  ); 
}
1

1 Answers

0
votes

The correct way to solve this is by using a server like nginx or apache to direct the traffic to the frontend or backend portion of the site.

You can also let the backend serve up your angular site. Run ng build (I am using the development configuration below) and have the outputPath in your angular.json file place the files into the server. e.g.

      "configurations": {
        "development": {
          "extractCss": true,
          "sourceMap": true,
          "watch": true,
          "poll": 1000,
          "outputPath": "../server/target/classes/static"
        }

You will need to do a bit of extra configuration to get everything served up but then the entire site would be located at localhost:8080.

You can also disable CORS in your spring security configuration with:

protected void configure(HttpSecurity http) throws Exception {
    http.cors().disable();
}

Although that is not the best long term solution.