Laravel Passport API Status Code:403 Forbidden

2019-08-26 22:21发布

问题:

I am developing an Ionic Mobile App that connects to the server in Laravel via REST API. I used the Laravel passport package and configured some stuffs on how authorization tokens will work on the API. So I write some code on providers for the Ionic app and I have this login function for the user in the mobile to logged in via API from the server but it keeps telling me this error:

Status Code:403 Forbidden

This seems to be a server side error that I don't have the permission to access this resources. Right?

So the server understood the request coming from the Ionic side but refuses it or forbidden by the server.

I used the CORS Allow-Control-Origin to connect Ionic apps to Laravel.

However when I tried to do a POST request using POSTMAN with all the grant types and client secret provided by the Laravel passport package it is successful that it give me the token type bearer, access token and the refresh token by the oauth.

Here is the code in my Middleware Cors

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

and here is the code in my api routes:

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api', 'cors')->get('/user', function (Request $request) {
    return $request->user();
});


Route::resource('departments', 'DepartmentAPIController');
Route::resource('users', 'UserAPIController');
Route::get('users/{username}', 'UserAPIController@getAccount');

Route::resource('inspection_checklists', 'InspectionChecklistsAPIController');

Btw I am using the getAccount function in the User API Controller.

Appreciate if someone can help. Thanks in advance.

回答1:

There is nothing to do with CORS. as stated in passport documentation:

The JSON API is guarded by the web and auth middlewares; therefore, it may only be called from your own application. It is not able to be called from an external source. That means you have to be logged in to use these routes.