Angular 2 HttpPost to Oauth2

2019-03-06 19:16发布

问题:

I'm doing an HttpPost and is giving to me error 401 but I've searched a lot on StackOverflow and I guess my call is OK, but the problem is when I execute this HttpPost on my ARC if I do not put the authorization: user:password it will popup a message saying this :

And I have to put it manually, BUT even if I do this :

It will pop up the Authentication required.

And it automatically changed to something like

authorization: Basic JvbnyZpZpzZWNTcHNQX=

And now, the code looks like this :

My headers

 private headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
 private apiUrl = 'https://myApiTest/oauth/token';




var auth = "Basic " + Base64.encode("test:test");//Also have tried to copy the hexgenerated by ARC
    this.headers.append('authorization', auth);
    var body = 'grant_type=password&username=test@test.com&password=test';
     return new Promise((resolve, reject) => {
      this.http.post(this.apiUrl,body, {
            headers: this.headers
          })
        .subscribe(res => {
          alert(res.json());
          resolve(res.json());
        }, (err) => {
          reject(err);
          console.log(err);
        });
    });

And this is the error given by console

XMLHttpRequest cannot load https://myApiTest/oauth/token. Response for preflight has invalid HTTP status code 401 OPTIONS https://myApiTest/oauth/token 401 ()

EDIT

I've build it on my Android and it works fine seems like a problem with Google Chrome, I've found to use this : C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:/Chrome dev session2" --disable-web-security but I'd like to use other way.

回答1:

My initial guess would be that the API doesn't allows a cross domain request(CORS) More on CORS -> CORS

You might need to add middle ware to your API to allow CORS There might be some headers to set here If you are using a node API you might wanna set headers.

res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,OPTIONS');



回答2:

You need to enable CORS.

In your server (https://myApiTest) and also your client requests.

  • For any domain: Access-Control-Allow-Origin "*"

  • For just one domain: Access-Control-Allow-Origin "https://your-exact-client-domain"

  • For multiple domains: https://stackoverflow.com/a/1850482/431841

Finally, I do not recommend you to disable the browser security, that should be your last resort.

Cheers!