1
votes

I am getting 401 error while sending post request using the angular code, when I inspected network request I found out that the headers are not being sent along the post request, please see the image:

auth.service.ts

login(username: string, password: string) {
    let httpHeaders = new HttpHeaders({
      'Authorization': 'Basic bXktdHJ1c3RlZC1jbGllbnQ6c2VjcmV0',
      'Content-Type': 'application/json'
    });
    let options = {
      headers: httpHeaders
    };
    this.http.post(
      'http://localhost:8080/SpringSecurityOAuth2Example/oauth/token?grant_type=password&username=bill&password=abc123',
      null,
      options
    ).subscribe(res => {
      console.log(res);
    },
      err => {
        console.log(err);
      }
    );
}

Request missing headers

enter image description here

Although CORS is enabled on my server, so doesn't seem to CORS issue

enter image description here

1
The request headers in the question seem to be for the CORS preflight OPTIONS request the browser automatically sends on its own. The reason that doesn’t include the Authorization header is the CORS spec requires browsers to never send the Authorization header or any other credentials as part of the the preflight OPTIONS request. So if the server you’re sending the request must allow unauthenticated OPTIONS requests — without need for the Authorization header — and if it doesn’t, the preflight will fail and the browser still stop right there and never even try the POST request from your code.sideshowbarker
@sideshowbarker Thanks for pointing out that, I made the changes to skip authentication for OPTIONS method and it worked. You saved my day!Palsri

1 Answers

0
votes
let options = {
  headers: httpHeaders
};

This should be a RequestOptions object not a plain object. Angular HttpClient wont recognize it. Change it to

let options = new RequestOptions({ headers: headers });