Friday, March 10, 2017

JWT Authentication in Laravel

I'm working on jwt (tymondesigns/jwt-auth) in a laravel 5.4 project and I'm new in both of them.

There is a simple sign in process. The end of this process a token is created and returned in a response.

return response()->json(['result' => true, 'message' => 'success message', 'token' => $token]);

Every thing is ok so far but after this I'm a bit confused.

I want to get the response in javascript and call another page which is defined in the route.

$.ajax({
    type: 'POST',
    url: '/api/signIn/',
    data: data,
    dataType: 'JSON',
    success: function (response) {
       if (response.result) {
         localStorage.setItem('token', response.token);

         // What should I do here ? 

       } 
    }
});

I'm using jwt.auth middleware in the route.

Route::get('/', function () {
    return view('signin');
});

Route::group(['middleware' => ['api'], 'prefix' => 'api'], function () {
    Route::post('signIn', 'APIController@signIn');
    Route::group(['middleware' => 'jwt.auth'], function () {
        Route::post('aFunction', 'APIController@aFunction');
    });
});


Route::group(['middleware' => 'jwt.auth'], function () {
    Route::get('/home', function () {
        return view('main');
    });
});

When I call 'home' in success of ajax request like window.location.href = 'home'; or load the url directly from browser, normally the process can not pass the token control because both are not json base request.

I need some advice for these questions.

How should I send the token and control it properly in requests which are not json base ?

Should I store the token both in client side and in server side (cache, session etc.) ?

Should I work on signin and home page as single page ?



via kbrk

Advertisement