JWT stand for Json Web Token. JWT will helps to create authentication and connect front-end and back-end function. JWT through we can create login and register API. So first we have to install “tymon/jwt-auth” package in laravel 5.2.
JWT Installation
First fire following command on your terminal.
Installation Package
composer require tymon/jwt-auth After install this package, Now open config/app.php file and add service provider and aliase. config/app.php
Now we need to publish JWT configration file, that way we can change configration like token expire time etc. so, let’s fire bellow command.
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider" At last on installation, we have to generate jwt key, fire bellow command on your terminal.
php artisan jwt:generate
Create API Route
Now we require to create create route for API, in bellow route you can see i use two middleware “api” and “cors”. cors is not mandatory, but when you call api and found like:
“Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://test.com/api/register. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).”
Then you have two must be create cors middleware by following link : Ajax - Cross-Origin Request Blocked in Larave 5?.
In above i use also added jwt-auth for token is valid or not. so we must need to create jwt-auth middleware and first fire following command.
php artisan make:middleware authJWT On now you can check on Middleware(app/Http/Middleware) directory, you can find authJWT.php file and put bellow code on that file.
Now we are ready to check our API from front-end side. i did make jquery ajax request example but you can also call API in angularjs. first fire register api that will return just success if user created success fully.
Call Register API
1 2 3 4 5 6 7 8 9
$.ajax({ url: "http://learnl52.hd/api/register", dataType: "json", type: "POST", data: {"name":"HD","email":"test@gmail.com","password":"123456"}, success: function (data) { alert("user created successfully") } });
Now you can fire login API, this API will return token in result if, email and password will not wrong. that token you have to pass in all other route that way you can identify this user is current login user so fire following way:
At last we can fire get_user_details API, This API will take only one paramete token, token is that you find on login API. this API will return all users details if your token is valid, if token is not valid then return error message. fire ajax like this way: