Angular2 How to get token by sending credentials

You might have two problems:

  1. The OPTIONS call is a preflight call. The CORS standard states that preflight calls should not include authentication. If your server isn't set up to handle that, you will get a 401 response. If you have control over the server you should be able to add something to allow the OPTIONS call through. With NGINX you can add something like:

    if ($request_method = 'OPTIONS') {return 200;}

    Not sure about you're particular server.

  2. Are you sure you are sending the credentials the right way? It looks like you are sending all this as individual headers rather than form-encoded data like you are with the curl request. This has worked for me:

    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    
    var credentials = "grant_type=authorization_code 
                    + "&credentials=true"
                    + "&scope=write" 
                    /* etc. */
    
    
    this.http.post('http://some.url', credentials, { headers: headers })
        .subscribe((res) => token = res.json())
    

You should provide the username / password hints within the Authorization header with the "Basic" scheme. The value must encoded with base64 with the btoa function:

headers.append('Authorization', 'Basic ' + btoa('username:password');

Moreover, after having alook at your curling request, it seems that what you put in headers should be provided in the payload. This can be done using the UrlSearchParams class.

See rhis question for more details:

  • Angular2 Http post request not binding to ASP.NET 5 controller's action