12

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)

Alec Fenichel
  • 1,257
  • 1
  • 13
  • 27
Gacci
  • 1,388
  • 1
  • 11
  • 23
  • 1
    Possible duplicate of [Where to store JWT in browser? How to protect against CSRF?](https://stackoverflow.com/questions/27067251/where-to-store-jwt-in-browser-how-to-protect-against-csrf) – pedrofb Nov 07 '17 at 09:12

3 Answers3

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

Daniel Tran
  • 6,083
  • 12
  • 25
  • 2
    If you store JWT in a cookie, you need to implement CSRF attack mitigations like a CSRF token. – Alec Fenichel Nov 07 '17 at 07:39
  • Yes, that's true. Most of modern website use javascript to call the API so we can use a custom header to make sure that the call is made from javascript, then we can avoid CSRF attach. – Daniel Tran Nov 07 '17 at 07:42
0

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.

SmartCoder
  • 413
  • 2
  • 13
  • 3
    JWT are very useful for web applications in browsers. They can be used for stateless authorization where the API is a distributed system. See https://jwt.io/introduction/ – Alec Fenichel Nov 07 '17 at 07:07
  • I believe I am still confused because I have seen articles where it reads "by bye session, welcome jwt's". So if, let's say I am making an application, let's say like Amazon where people post to sell stuff and have my databases Do I use sessions or jwt. Sounds like I should use both because if i make my database information accessible through an API I should use jwt as well. Also, could you please explain browser application and hybrid application. – Gacci Nov 07 '17 at 07:16
  • You probably don't need both JWT and sessions. If you chose to use JWT, you have two (three ish) options for storage, cookies or local storage (session storage is similar to local storage). I would start with local or session storage as it will be the fastest to implement. See https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage – Alec Fenichel Nov 07 '17 at 07:21
0

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.

Maximilian Fixl
  • 670
  • 6
  • 23