How to setup jwt authentication laravel 4

By: Ryan Wong at

When trying to authenticate mobile application with laravel back end server, you cannot use the default session you would use in php. The common practice for authenticating is using json web tokens.

##Steps:
1.Depending on which version of laravel you are using install the correct plugin for laravel cors with composer.
I’m using laravel 4 so I used:

1
composer require barryvdh/laravel-cors:0.2.x

2.Next I created the config file with

1
php artisan config:publish barryvdh/laravel-cors

3.Next I modified the config file in app/config/packages/barryvdh/laravel-cors/config.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
'defaults' => array(
'supportsCredentials' => false,
'allowedOrigins' => array(),
'allowedHeaders' => array(),
'allowedMethods' => array(),
'exposedHeaders' => array(),
'maxAge' => 0,
'hosts' => array(),
),

'paths' => array(
'api/v1/*' => array(
'allowedOrigins' => array('*'),
'allowedHeaders' => array('*'),
'allowedMethods' => array('*'),
'maxAge' => 3600,
)
)

You can use whatever route you want, I just used /api/v1.

4.Next install jwt plugin. Depending on your version of laravel, install a different version of the plugin with composer.

1
composer require tymon/jwt-auth:0.4.*

5.Next I created the config file with

1
php artisan config:publish tymon/jwt-auth

You can change the jwt settings here if you want.

6.Next you will create a filter to check for jwt token before processing a route. I put the filter in my route.php file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Route::filter('authMobile', function($route, $request)
{

try{
$token = JWTAuth::getToken();
$user = JWTAuth::toUser($token);
$tokenStr = JWTAuth::getToken()->__toString();
if ($user->loginToken != $tokenStr){
throw new Exception("Login Token don't match");
}
Session::put('user',$user->id);
}catch(Exception $e){
return Response::json(array(
'error' => true,
'message' => 'Invalid Session'
));
}
});

7.So an example route will look like the following:

1
2
3
4
Route::get('/api/v1/user', array(
'before' => 'authMobile',
'uses' =>'UsersController@getUserProfile'
));

To access the user in the action, you can retrieve it from the session.

  1. When creating the login, you would return the following JSON to the mobile app.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    //validation happens jere
    $row = User::find(Auth::user()->id);
    $token = JWTAuth::fromUser($row);

    DB::table('users')->where('id', '=',$row->id )->update(array(
    'last_login' => date("Y-m-d H:i:s"),
    'loginToken' => $token
    ));
    return Response::json(array(
    'token' => $token
    ));
    }

9.Now everytime the mobile app makes a request to the server, they must add a header

1
Authorization bearer Y2E1YTc2MmFkMWU4NjJmZTBiZDU1NmEzMmJhZjBmYjc3MmNkYzBiYjE3YWM5MTkxNDg2Zg...

10.Make sure your .htaccess file allows HTTP authorization.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>

RewriteEngine On

RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

Hope this helps you out.