Where to store JWT

Viewed 6556

I barely started reading about JWT and I beliave I understand what a JWT token is. I am also fairly familiar with SESSIONS. And I believe I understand the pros of each as well as their cons. However, there are a couple of parts where I am confused.

When requesting a protected resource, you need to send the jwt on each request, as opposed to having a session stored on the server. But:

1) how do you store your JWT token and where. From what I read I understood that you send your request to authenticate to the server and the server sends you a JWT token if you are successfully authenticated. Then what do you do?, do you store the JWT in a cookie as I have read in some sites? If so, how do you do it (using php, using javascript). And how do you read it.

2) When using session, more or less you just check that there is a session to check the user is logged in. How do you accomplish this when using JWT.

Also I have seen this on some pages:

RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

How is this related to this (if related at all)

3 Answers
  1. From client side, the good practice is store JWT in cookie, with mode http_only=true, is_secure (so that only send through https), so that JWT is not accessible by javascript. Then, we don't worry about XSS attach.

  2. We dont need to store the session on server side. A JWT contains two parts, the payload data, and signature, signed by a secret key stored on server side, and only the server could know. When we receive the token from client, we check the payload data is valid or not (user information, who assigned that token, assigned that token to whom, which roles granted with the token, expired time), and we check the signature to make sure that the token is assigned by the server, not faked. Then the user will be authenticated.

It's like a passport the government give to its citizen, the data (payload) is readable for everybody, but the signature can only created by the government, and it can verify against that.

JWT is mostly a way to authenticate a user on rest APIs as, like you said, you send it to the client, and it negates the need to store it in a session.

however, if you are making a browser application, i don't see the need to use JWT authentication, as you can use the session and cookies to do so.

JWT is mainly for those cases, when you have a, say, mobile application frontend, where maintaining a session is not suggested, and maybe impossible.

however, if you are making a hybrid application, then storing it in local storage of the "browser" is the way to go. the JWT is NEVER stored server side.

In my case I use use Illuminate\Foundation\Auth\AuthenticatesUsers;, use JWTAuth; and use Tymon\JWTAuth\Exceptions\JWTException; in my LoginController. Then I need to get my JWTToken like that

use AuthenticatesUsers;

try {
   $token = JWTAuth::attempt($request->only('username', 'password'), [
   'exp' => Carbon::now()->addWeek()->timestamp,
   ]);
} catch (JWTException $e) {
    return response()->json([
        'error' => 'Could not authenticate: ' . $e.message,
    ], 500);
  }

Of cause I do somthing more, if I don't get a token. In my case I go like that:

if (!$token) {
    return response()->json([
        'error' => 'Could not authenticate.'
    ], 401);
} else {
    $data = [];
    $meta = [];

    //all what i need from users table if auth
    $data['id'] = $request->user()->id;
    $data['email'] = $request->user()->email;

    $meta['token'] = $token;

    //now comes the part, where I set my sessions:

    Session::put('auth-user', (array)$request->user());
    Session::put('jwt-token', $token);
    Session::save();

    return response()->json([
            'data' => $data,
            'meta' => $meta
        ])->withCookie('jwt-token', $token, config('jwt.ttl'), '/', null, true, true);
}

This is actually that what I do in LoginController I also have a middleware where I have a function to handle stuff like behavior after refresh page an so on.

'my.auth' => \App\Http\Middleware\MyAuth::class

I also handle a lot in javaScript's localStorage and sessionStorage in vuex store. To define routes in web.php or api.php I'll use now the class what I defined in middleware before Route::group(['middleware' => 'my.auth'], function(){...}

Some resources that helped me out: LaravelCookies, LaravelSession

Hope you get a bit inspiration to create your JWT auth.

Related