1
votes

I want to request Token from API with:

Signin(email: string, password: string): void {
    let data: Object = {
        client_id: 2,
        client_secret: 'vSFxVqALQHjyotPyGfhrGj3ziudUGsts2ZWiAGms',
        grant_type: 'password',
        username: email,
        password: password,
    };

    this._HTTP.post(
        this.OAuth + 'token',
        data,
        {headers: this.Headers}
    ).toPromise()
    .then( (_response) => {
       console.log (_response); 
    });
}

And i receive an error with 401 Unauthorized

21:54:03.996 ERROR Error: Uncaught (in promise): Response with status: 401 Unauthorized for URL: http://localhost:8000/oauth/token

I don't understand why I get this error, I added in Kernel -> middleware -> web this:

\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
1

1 Answers

0
votes

Yo should use content-type application/x-www-form-urlencoded and have your angular service like this:

 import { Injectable } from '@angular/core';
 import { HttpClient, HttpHeaders } from '@angular/common/http';
 import { Observable } from 'rxjs';
 import { map } from 'rxjs/operators';

 import { environment } from '../../../environments/environment';
 import { HttpApi } from '../http/http-api';

 const OAUTH_DATA = environment.oauth;

 @Injectable({
   providedIn: 'root'
 })
 export class AuthenticationService {

   constructor(private http: HttpClient) { }

   public loginWithUserCredentials(username: string, password: string): Observable<any> {
     let headers = new HttpHeaders();
     headers = headers.set('Content-Type', 'application/x-www-form-urlencoded');

     const body = new URLSearchParams();
     body.set('grant_type', 'password');
     body.set('client_id', OAUTH_DATA.client_id);
     body.set('client_secret', OAUTH_DATA.client_secret);
     body.set('username', username);
     body.set('password', password);
     body.set('scope', OAUTH_DATA.scope);

     return this.http.post(HttpApi.oauthLogin, body.toString(), {headers: headers})
       .pipe(map((response: any) => {
           localStorage.setItem('session', JSON.stringify(response));
           return response;
        }));
   }

}

In laravel:

  1. Passport configuration (changes: https://github.com/dedd1993/laravel-oauth2-server/commit/da17f500be60958378be898021414383b541961e).
  2. Add cors (https://github.com/barryvdh/laravel-cors), here an example https://github.com/dedd1993/laravel-oauth2-server/commit/e0b942cd3674fd0464cdbb3572cf7a8bd7849755
  3. Finally, group your APIS inside auth middleware, here an example https://github.com/dedd1993/laravel-oauth2-server/commit/5b05538e2d102e00949edc667b85df102f770186

I have both examples

Angular full proyect: https://github.com/dedd1993/ngx-admin

Laravel basic oauth: https://github.com/dedd1993/laravel-oauth2-server