javascriptrestcorsfetch-apialm

Authorization against REST API throws an error: 401 (No credentials found the request.)


I want to authorize against the HP Alm Rest API, I think this "should" work, but it does not:

function performSignIn(){

let headers = new Headers();

headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));

fetch(sign_in, {mode: 'no-cors', method:'POST', headers: headers})
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(error => console.log('Authorization failed : ' + error.message));
}

I get a bit weird error message:

401 (No credentials found the request.)

This is an example from the HP documentation, done with XMLHttpRequest: http://alm-help.saas.hpe.com/de/12.53/api_refs/REST/webframe.htm#signin-out_example.htm

Any idea? I don't see what's wrong.

Thank's a lot!

Best regards, Daniel


Solution

  • fetch(…) by default doesn’t send credentials. You need to explicitly specify they should be sent:

    fetch(sign_in, {credentials: 'include' , method:'POST', headers: headers})
      .then(response => response.json())
      .then(json => console.log(json))
      .catch(error => console.log('Authorization failed : ' + error.message));
    }
    

    Also, incidentally, you definitely don’t want to specify mode: 'no-cors'. The effect that has is to tell the browser, Block my frontend JavaScript from accessing the response from this request.