Laravel Passport JWT Authentication

I was having a very hard time to figure out a way to integrate JWT authentication using Laravel Passport and was under a dilemma whether this is at all possible.

After spending a decent amount of time I finally figured out that JWT authentication can be done easily using Laravel passport.

First of all follow the steps mentioned in the Laravel Passport installation documentation.

Once this is done, next we will create a User controller and add an auth() method where we will authenticate the username and password of the user and generate a token against it, which we will return in the same request.

Step 1: Create a UserController

 

Step 2: Add an auth method in the UserController. This method will be responsible for authenticating the specified username (email) and password.

 

Step 3: Create an index method within the UserController. This method will be responsible to return the logged in user’s details.

 

Step 4: Creating the routes. Open the routes/api.php file and add the following two routes in it:

 

Step 5: Now make a POST request to http://localhost:8000/auth with the email address and password as shown in the screenshot. This will get you the accessToken, you can use this token to make other requests in your application with the Authorization header and Bearer XXX where xxx is the accessToken you received from /api/auth endpoint.

Step 6: Now, make a GET request to /api/user with the Authorization header and the token value, this will return the authenticated user’s details.

 

I hope this will be useful for you all.