Dingo/Api and JWT auth

789 Views Asked by At

I'm looking for the way to implement auth with JWT and Dingo/Api. I've added JWT package to my project. Added 'jwt' => 'Dingo\Api\Auth\Provider\JWT', into my api.php auth part.

And also added into my BaseController

public function __construct()
    {
        $this->middleware('api.auth');
    }

How do I check if the user has permission (by role) using FormRequest? It has an authorize method, however I'm not sure how to get my user.

Since I'm using JWT the token is sent in the headers.

2

There are 2 best solutions below

0
Edrian On

One way to do it is to adding the role validation to the middleware.

You can try adding this custom validation to the part where it verifies the JWT the user gave as that is the part where you can determine who is the user that owns the token.

0
Tschitsch On

You can use the Auth Facade to retrieve the currently authenticated user:

$user = \Auth::user()

For authorization you can use policies, see https://laravel.com/docs/5.6/authorization Once enabled you can check for a users ability in your authorize method(s), e.g.

public function authorize() {
    $user = \Auth::user();
    return $user->can("do-something");
}

But there are multiple possibilities how to perform authorization checks, read the docs mentioned above for more details.