Enabling CORS in Laravel 5.x

If you have built your RESTful api using laravel chances are your fontend developers will face problems talking to your api with javascript. They might see errors in your Dev tool console like the following

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com. This can be fixed by moving the resource to the same domain or enabling CORS.

The way you can fix this is by introducing a CORS middleware in your laravel app and register it. Its simple than you can even think of.

Step 1

Lets create a new middleware and name it Cors

A file will be created at app\Http\Middleware

Step 2

Open the newly create file Cors.php from the above path and replace the content of the handle() method with the following

Step 3

Open app\Http\Kernal.php and register your Cors middleware by adding the following code in the $middleware array.


Step 4

No step 4. You should be all set.



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.