Search code examples
angularlaraveltypescriptlaravel-passport

unsupported_grant_type error when I try to authenticate a user


I know that there has been a lot of questions and answers about what I am going to ask but none of them has solved my problem.

Now, I am developing an angular 5 application and I am trying to get an authentication token by sending post to a server. When I use postman to test the connections there is no problem. But in angular I get the following error

400 (Bad Request) "unsupported_grant_type"

Here is what I wrote so far,

getAccessToken2() {
let url = "http://api.akilli.tv/oauth/token";

var headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Accept', 'application/json');

let urlSearchParams = new URLSearchParams();
urlSearchParams.set('grant_type', 'password');
urlSearchParams.set('username', 'alikamilyagli@gmail.com');
urlSearchParams.set('password', '1234');
urlSearchParams.set('client_id', '2');
urlSearchParams.set('client_secret', 'Q5U9fclient*!secret*!clientsecret*!9SqUaH9sKro');
urlSearchParams.set('scope', '*');

let body = urlSearchParams.toString();

return this.http.post(url, body)
  .subscribe((data: any) => {
    console.log(data);
  });

}

And here is a screenshot of postman request which was succesfull enter image description here

And I have also faced with the Access-allow-control-origin problem and solved by adding a chrome add-on which is called "CORS". Is there another and healthier way of solving this?

Thanks in advance already.


Solution

  • Try this

    const data = 'grant_type=password';
            return this.http.post( url, data,
                {headers: new HttpHeaders({'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'})});