tymondesigns / jwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen
https://jwt-auth.com
MIT License
11.3k stars 1.54k forks source link

Laravel 5.3 Policies not working with jwt #940

Open akrami opened 7 years ago

akrami commented 7 years ago

I'm trying to use policies for my API but it seems that policies do not run with JWT. https://laravel.com/docs/5.3/authorization#creating-policies

any workaround or fix?

woriheck commented 7 years ago

Register Middleware to the route

screen shot 2016-12-28 at 11 27 02 am

Route::group(['middleware' => 'jwt.auth'], function () { // your api url });

Then the login user may be get inside laravel policy.

screen shot 2016-12-28 at 11 34 13 am https://laravel.com/docs/5.3/authorization

engAhmad commented 7 years ago

make sure the user_id is integer number or cast it

"1" === 1 False

diquinnyonk commented 7 years ago

I had same issue but I had a general check to make (which would've been nice to use in before() ) but instead opted to use a middleware

masoudline commented 7 years ago

can i use laravel policy and jwtAuth inside project?

and how?

JenteVH commented 6 years ago

Wondering also for laravel 5.6 and jwt-auth 1.0.0-rc2 Can't get policies to work together with this.

bambamboole commented 6 years ago

I have the very same problem with laravel 5.7 and jwt-auth@1.0.0-rc.3. @tymondesigns do you know whats the issue with policies?

bambamboole commented 6 years ago

Ok I figured it out.

Adding a middleware like this to the App\Http\Kernel

    protected $routeMiddleware = [
        //...
        'jwt.auth'      => \Tymon\JWTAuth\Http\Middleware\Authenticate::class,
    ];

and using in routes like this

    Route::group(['middleware' => ['jwt.auth']], function () {
       Route::post('/auth/logout', 'Api\AuthController@logout')->name('api.auth.logout');
       Route::post('/auth/refresh', 'Api\AuthController@refresh')->name('api.auth.refresh');
    });

solves the authentication problem :-)

For nice json error messages i customized render moethod of the App\Exceptions\Handler like this;

    public function render($request, Exception $exception)
    {
        if ($exception instanceof UnauthorizedHttpException) {
            return response()->json(['error' => $exception->getMessage()], $exception->getStatusCode());
        }

        return parent::render($request, $exception);
    }

It's just normal laravel middleware.

stale[bot] commented 3 years ago

Is this still relevant? If so, what is blocking it? Is there anything you can do to help move it forward?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.