laravel5.2使用JWT

more less

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

1
2
3
4
5
6
7
8
'providers' => [
....
'Tymon\JWTAuth\Providers\JWTAuthServiceProvider',
],
'aliases' => [
....
'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth'
],

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?.

app/Http/routes.php

1
2
3
4
5
6
7
Route::group(['middleware' => ['api','cors'],'prefix' => 'api'], function () {
Route::post('register', 'APIController@register');
Route::post('login', 'APIController@login');
Route::group(['middleware' => 'jwt-auth'], function () {
Route::post('get_user_details', 'APIController@get_user_details');
});
});

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.

app/Http/Middleware/authJWT.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace App\Http\Middleware;
use Closure;
use JWTAuth;
use Exception;
class authJWT
{
public function handle($request, Closure $next)
{
try {
$user = JWTAuth::toUser($request->input('token'));
} catch (Exception $e) {
if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
return response()->json(['error'=>'Token is Invalid']);
}else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
return response()->json(['error'=>'Token is Expired']);
}else{
return response()->json(['error'=>'Something is wrong']);
}
}
return $next($request);
}
}

Ok, now register new created middleware on Kernel.php(app/Http/Kernel.php) file and append following line.

app/Http/Kernel.php

1
2
3
4
5
6
7
8
9
10
11
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
...
...
protected $routeMiddleware = [
...
'jwt-auth' => \App\Http\Middleware\authJWT::class,
];
}

Create Controller

Here we have to create controller that will manage all route request. so first create “APIController” and put bellow code.

app/Http/Controllers/APIController.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Hash;
use JWTAuth;
class APIController extends Controller
{

public function register(Request $request)
{
$input = $request->all();
$input['password'] = Hash::make($input['password']);
User::create($input);
return response()->json(['result'=>true]);
}

public function login(Request $request)
{
$input = $request->all();
if (!$token = JWTAuth::attempt($input)) {
return response()->json(['result' => 'wrong email or password.']);
}
return response()->json(['result' => $token]);
}

public function get_user_details(Request $request)
{
$input = $request->all();
$user = JWTAuth::toUser($input['token']);
return response()->json(['result' => $user]);
}

}

Test API from Front-end

Don’t forgot to change http://learnl52.hd = your site url.

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:

Call Login API

1
2
3
4
5
6
7
8
9
$.ajax({
url: "http://learnl52.hd/api/login",
dataType: "json",
type: "POST",
data: {"email":"test@gmail.com","password":"123456"},
success: function (data) {
alert(data.result)
}
});

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:

Call Get User Details API

1
2
3
4
5
6
7
8
9
$.ajax({
url: "http://learnl52.hd/api/get_user_details",
dataType: "json",
type: "POST",
data: {"token":your toke here},
success: function (data) {
console.log(data)
}
});

add

Require the barryvdh/laravel-cors package in your composer.json and update your dependencies.

composer require barryvdh/laravel-cors
Add the Cors\ServiceProvider to yourconfig/app.phpproviders array:

Barryvdh\Cors\ServiceProvider::class,

http://itsolutionstuff.com/post/laravel-52-api-using-jwt-authentication-tutorial-from-scratch-exampleexample.html