Search code examples
phpangularlaravellaravel-passport

Laravel 5.4, Passport, and Angular 7 not playing nicely together


I've got a site that I've built using Laravel 5.4 that I'm working on updating the UI on. I want to go in the direction of a Single Page Application using Angular 7. However I'm stuck trying to make a request to my API endpoint I keep getting a 401 error. I've followed the instructions here: https://laravel.com/docs/5.4/passport#consuming-your-api-with-javascript added the meta tag to the page, did the additional setup, and started using Angulars HTTP library like so

this.httpOptions = {
    headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN': this.meta.getTag('name=csrf-token').content
    })
};

this.http.get('api/v1/people', this.httpOptions).subscribe((data: any) => {console.log(data); });

however I continue to receive the 401 error. In addition here are the Kernel.php

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,       
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class
    ],

    'api' => [
        'throttle:60,1',
        'auth:api'
    ],
];

and Routes.php

Route::group(['middleware' => 'auth:api'], function(){
   Route::group(['prefix' => 'api/v1'], function () {
     Route::get('people', 'personController@apiIndex');
     Route::get('person/{id}', 'personController@apiGetPerson');
     Route::post('contactevent', 'contactEventsController@apiAddContactEvent');
   });
});

Any input would be appreciated.


Solution

  • Looks like I misunderstood some of the documentation provided. When you want to consume your api through javascript that you serve up on your site you don't have to include your route in the auth:api group to authenticate the call. Laravel instead passes a cookie with your request additionally CSRF isn't needed unless it's a POST request. My solution was to move my route to the auth middleware group like so:

    Route::group(['middleware' => 'auth'], function () {
      Route::get('api/v1/people', 'personController@apiIndex');
    }
    

    And to rewrite my Angular HTTP request like so:

    this.httpOptions = {
        headers: new HttpHeaders({
            'Content-Type':  'application/json'
        })
    };
    
    this.http.get('api/v1/people', this.httpOptions).subscribe((data: any) => {console.log(data); });
    

    And everything worked as expected.