JSON Web tokens vs sessions for authentication | should you use JWTs as session tokens?

Sdílet
Vložit
  • čas přidán 27. 07. 2024
  • 🔥More exclusive content: productioncoder.com/you-decid...
    Twitter: / _jgoebel
    Blog: productioncoder.com
    In this video we cover whether you should use JSON Web tokens as session tokens. The answer might surprise you.
    Mentioned blog posts for further reading
    cryto.net/~joepie91/blog/2016/...
    cryto.net/~joepie91/blog/2016/...
    00:00 should you use JWTs as session tokens?
    00:26 how server-side sessions with a session store work
    01:55 how "client-side" sessions with JWTs work
    04:03 logging out users from the server side
    05:22 knowing who is currently logged in
    06:11 session data visibility
    06:42 revoking roles and privileges in JWT and session-based systems
    08:00 scalability of server-side and client-side sessions
    08:58 the need to maintain a session store
    09:16 bandwidth consumption
    09:38 attacking JWTs vs session-based authentication
    11:11 cookies vs local storage
    11:54 mitigating CSRF attacks

Komentáře • 133

  • @jgoebel
    @jgoebel  Před 4 lety +9

    Let me know what you think about this video.
    Feel free to also post any video ideas in the comments below

    • @user-gg5nh1mf6l
      @user-gg5nh1mf6l Před 4 lety +1

      could u please make a project tutorial in nodejs, express and mongodb?
      you explain every line of code, that's why I love your video.
      thanks

    • @jgoebel
      @jgoebel  Před 4 lety +1

      will add that to my list of potential topics as well 👍

    • @MahadyHasan
      @MahadyHasan Před 2 lety

      Thank you so much for your very well explanation. Last one week I am searching for a solution for browser and server base communication for my Web app. I can't come to a conclusion which one: JSON Web tokens OR server base sessions approach will be better even tho I have been implemented a server base session storage approach from the beginning. Now really I can visualize the situation. JWT is really mess. But one-time link validation (e.g. forgot password) would nice approach with JWT. Am I right?

    • @hoangdaoduc6610
      @hoangdaoduc6610 Před 2 lety

      Thanks you for your your explanation. I have a question, do you think session and cookies authentication is not good for mobile app development? Do sessions and cookies work only for web?

  • @jmrah
    @jmrah Před rokem +4

    Lucid and cogent talk. I learned quite a bit. Thanks for taking the time to put this together.

  • @austinmusiku778
    @austinmusiku778 Před 3 lety +5

    This is really really good. Your well articulated points backed by nicely done illustrations helped me better understand the concepts

    • @jgoebel
      @jgoebel  Před 3 lety +1

      thx, I'm glad it was helpful 👍

  • @paulgreen4161
    @paulgreen4161 Před rokem

    Nice presentation - I had come to the same conclusion but you cover it and explain it really well!

  • @hagridhaired
    @hagridhaired Před 3 lety +5

    Super helpful and clear! Thank you for this great video.

  • @thekeykan
    @thekeykan Před 3 lety +2

    Super duper helpful! Thank you for the great explanation. It is really thoughtful, easy to understand and clean. 👌

  • @sergiim5601
    @sergiim5601 Před 3 lety +2

    You are producing amazing content. Thank you a lot !

    • @jgoebel
      @jgoebel  Před 3 lety

      thx Sergii, I'm glad you are enjoying it 👍

  • @paulwong7224
    @paulwong7224 Před rokem +1

    Also thanks so much for this video. I learned a lot. I feel like the comparison has been so confusing and unclear. I now understand either way we're storing sessions, it's just whether you store them server side in a session store like redis OR client side via a JWT on the browser. That really clarifies the argument for me. In addition, all the other info in this video and your other videos are excellent explanations! Thanks you.

  • @furqananwar8449
    @furqananwar8449 Před 2 lety +2

    I didn't even think about these scenarios (drawbacks ) of JWT. Thanks for sharing 🙂

    • @jgoebel
      @jgoebel  Před 2 lety +2

      Glad it was helpful!

  • @abhishekbehera8208
    @abhishekbehera8208 Před 2 lety

    Thank you for this wonderful video with so much information yet, so simple to understand!

  • @karlopest9288
    @karlopest9288 Před 2 lety +2

    This video made me change my mind about JWT. Great content here

  • @dataluchs1288
    @dataluchs1288 Před 3 lety +1

    This was helpful, thanks! More informative content like that please

    • @jgoebel
      @jgoebel  Před 3 lety

      glad you liked it 👍

  • @davidkuda
    @davidkuda Před rokem +1

    Hey man, this was really helpful and insightful, I like how you put together the table and summarised the topic there. Thanks for creating this content.

    • @jgoebel
      @jgoebel  Před rokem +1

      Glad it was helpful!

  • @HaraldEngels
    @HaraldEngels Před 2 lety +3

    I was always considering to switch from my battle-tested (APCu/Redis) session based solution to JWT. You successfully dissuaded me. Thank you for opening my eyes.

  • @moolipit
    @moolipit Před rokem +5

    Case #6: Need to maintain session store - I'd say its also "Yes" for JWT since you need to maintain a token blacklist. So it's yes for both and you better off maintaining whitelist (session than a blacklist (JWT)

    • @jgoebel
      @jgoebel  Před rokem +2

      yes, if you want logout functionality, you need to maintain a blocked list. The thing is that this is also dangerous because if the your blocked list cache goes down, the blocked tokens are all of a sudden valid again. Now of course if your session store goes down, everybody gets locked out, too. This is also not good, but at least nobody is getting access who should not have access.
      Sessions become challenging in big systems and microservice-based systems though

  • @atharva1237
    @atharva1237 Před 2 lety +1

    Very good explanation thank you!

    • @jgoebel
      @jgoebel  Před 2 lety

      you're most welcome Atharva 👍

  • @Daniel-nb3kk
    @Daniel-nb3kk Před 3 lety +1

    Thanks, very useful to know! :)

  • @bernardodomeneghetti9673
    @bernardodomeneghetti9673 Před 11 měsíci

    Thank you for processing so much information for this vídeo

    • @jgoebel
      @jgoebel  Před 10 měsíci

      Glad it was helpful!

  • @VishnuBharathi
    @VishnuBharathi Před 4 lety +1

    Nice explanation!

    • @jgoebel
      @jgoebel  Před 4 lety

      thanks, I'm glad you like it 👍

  • @alirezarezaeikalat9421
    @alirezarezaeikalat9421 Před 2 lety +1

    It was a great explanation

  • @Cognitoman
    @Cognitoman Před rokem

    Damn 😂 this changed my mind on JWT by a lot... I already knew they had issues... but after watching this and read blog posts... I can’t think of any good reason to use them, except for maybe verifying emails for created accounts on your website😂...

  • @dios8256
    @dios8256 Před 7 měsíci

    Great video thanks

    • @jgoebel
      @jgoebel  Před 6 měsíci

      Glad you enjoyed it

  • @dfrontierit2114
    @dfrontierit2114 Před 2 lety

    I like this video. It makes me trust my policy more.. "Modern practices may sometimes not be the best choice until field tested over many years". Let me know if i am thinking wrong

    • @jgoebel
      @jgoebel  Před 2 lety

      I agree, I always try to use the simplest thing that works. In a simple setup without OAuth and OIDC, sessions are just fine

  • @user-ur4ev7vl6c
    @user-ur4ev7vl6c Před 2 lety +1

    JWT for microservices, Sessions for monolith(Load balance too)

  • @rajarshibarman4474
    @rajarshibarman4474 Před 2 lety +2

    damn you convinced me sessions are better than jwts... hats off brilliant explanation bro

    • @jgoebel
      @jgoebel  Před 2 lety +1

      thx Rajarshi 👍

    • @rajarshibarman4474
      @rajarshibarman4474 Před 2 lety

      @@jgoebel i had one doubt though... what if the client changed the session id in the cookie? will then the user have a chance to get the session of another logged in user? (lets say the client tries a bruteforce and generates a lot of session ids and some of them match session ids stored in redis session store)

    • @jgoebel
      @jgoebel  Před 2 lety

      @@rajarshibarman4474 session ids are typically not guessable because they are very long strings with sufficient entropy. In addition the most common session implementations actually HMAC or digitally sign at least the session id in the cookie to prevent brute force attacks (e.g. as far as I remember express-session HMACs the session id in the cookie). As usual the cookie should have the HttpOnly and Secure flags and have at least SameSite: Lax or SameSite: Strict (although SameSite: strict will probably have some negative UX implications).

    • @rajarshibarman4474
      @rajarshibarman4474 Před 2 lety +1

      @@jgoebel oh ok HMACs fix the problem of the user tampering the session id I see... (saw your HMAC video) thanks👍

  • @sto2779
    @sto2779 Před rokem

    Is it possible you can make a video about how to do some form of session management for guest users (users who does not want to log in and simply just browse the website, such as an eCommerce website).

  • @garriual
    @garriual Před rokem +1

    Very helpful! A few questions
    1. 4:07 - for logout user from the server side, does that mean you can have just one logged-in user with the same username at once with server-session approach?
    2. What about storing the session data on the client within a cookie? assuming the session we are storing is light and small. Does that take the best from both worlds 4:08? I'm not sure if we can logout user from the server side in that case though

    • @goldfishbrainjohn2462
      @goldfishbrainjohn2462 Před rokem

      1. For logging out a user, just delete the session from the DB or make it expired.
      2. why do you want to keep session data in Cookie if you can just store non-sensitive data in the local storage or session storage on the client side? Also, remind you, Cookie space is about 4KB. it's not suitable for large data.

  • @umut9780
    @umut9780 Před 3 lety +3

    This video was very very good at clearing the constant circle in my head of choosing which one to implement (for best practice purposes). I struggled to choose which one for a front-end client to server.
    A lot of the resources basically say yeah sure here's the pros and cons, which I can comprehend well enoguh. But never a clear cut answer from someone who is experienced on which one to actually use in best practice.
    Deep down I did also have the idea that JWT is better for server-server situations.

    • @jgoebel
      @jgoebel  Před 3 lety +1

      thx, I totally agree that JWT is good for server to server communication. JWTs are just no that well suited for client side sessions

    • @umut9780
      @umut9780 Před 3 lety

      @@jgoebel I know this is a different approach all together. However, is it fine if someone properly implements OAuth/OIDC?
      By properly I mean I know it has to be implemented abosolutely right. I've had some hands on experience with it too but there is a JWT exchange from client to server too. So I thought I'd ask your opinion.

    • @jgoebel
      @jgoebel  Před 3 lety +1

      Hi Umut, the OAuth 2 spec itself does not require you to use JWTs as access tokens - although a lot of people are doing that - simply because otherwise you would need to store the access token somewhere. Honestly, not sure why people (including myself) sometimes insist on sessions but are fine with self-encoded tokens like JWTs when it comes to OAuth2. That's why this is a very good question.
      To be able to immediately log someone out with OAuth2, you would need need a stateful solution because you would need to store the access tokens somewhere (or a list of blocked access tokens). To my knowledge, using JWTs with OAuth2 is quite common.
      This website here offers a nice explanation about token revocation with self-encoded tokens (like JWTs): www.oauth.com/oauth2-servers/listing-authorizations/revoking-access/

  • @turomatulic
    @turomatulic Před 3 lety +1

    awesome, loved it

    • @jgoebel
      @jgoebel  Před 3 lety +1

      thx Arturokin12, I'm glad you liked it 👍

  • @kregiel16
    @kregiel16 Před 3 lety +1

    What type of atuhentication would you recommend for typical SPA-Server(user accounts) application?

    • @jgoebel
      @jgoebel  Před 3 lety +3

      Hi kregiel, that would depend on what your security requirements are and what type of application you write. If you write a for consumers, I'd probably just use OAuth2 and OpenId Connect (e.g. Login with Google, Login with FB, etc). Like so you can offload of the authentication work to a federated identity provider which can even do 2FA without additional for you.
      Although the login with Google functionality would be based on tokens, Google would keep an invalidated list of tokens for you. Like so you do not have to bother with authentication yourself and it is easier for the user because he does not need to remember a password. So basically I would not attempt to implement some "blocked list" of tokens on the server side. There are also federated identity providers for the enterprise.
      If this is not an option (e.g. in banking for example), I would go with session. But ultimately from an SPA perspective, it depends on what the server supports

  • @griftegrd
    @griftegrd Před rokem

    I made a web app using JWT, now i need to implement a session based system to allow only one sesion per user. I wish I knew this first, guess Ill have to switch my entire implementation to session storage. Sigh...
    Thanks for this informative video!

  • @csakdee
    @csakdee Před rokem +1

    Most part of this is factually correct and simply explained, but JWT "sophystication" has nothing to do with it's safety. Both of them have their own use-cases.
    Same domain? Use session HTTP only cookies, if You can. But in a federated ID model You probably have to use tokens (oauth/OIDC) anyway.
    The JWT can have an expires-at field, and services SHOULD respect that. The only time window to exploit a stolen token is while it is not expired and the access token revoked (probably shorter time span than calling Yout bank or service to log You out).
    The IETF has an RFC document (RFC-7662) on "token introspection endpoints" of the identity provider/oauth server, so for critical services it is possible to "double-check" the token's validity giving the opportunity to effectively invalidate "instantly" any known bad tokens.
    So i would say the token authZ model is pretty safe to use (and in some scenarios maybe Your ONLY option) - but indeed, if You implement it wrong (or use a badly implemented dependency) it can be vulnerable.

  • @priceless5386
    @priceless5386 Před 4 lety +1

    what about on mobile apps. I thought that was why JWT sort of took off in popularity, because mobile app dont use a browser and cookies?

    • @jgoebel
      @jgoebel  Před 4 lety +6

      With apps it is a different story. Because in an app you can save the token somewhere where only the app has access to. So in that regard, it is not that problematic. It is only problematic once you are using a browser because of all the issues mentioned in the video

  • @paulwong7224
    @paulwong7224 Před rokem

    I wonder what your thoughts are on this when considering refresh tokens and access tokens for sessions stored via the client side in a JWT. Does it make it better that you can reduce the time the access token is available? Access tokens are usually say 15minutes, and I guess you already addressed that it wouldn't stop a bad actor within that 15 minute timeframe. Even with refresh tokens, I don't believe that access token can be revoked within that 15 minutes, so it makes no difference. So unless the access token expires after say 3-5 minutes, there's no changes to your pros and cons even if someone uses a refresh and access token along with a session stored on a client side cookie in a JWT right?

    • @paulwong7224
      @paulwong7224 Před rokem

      Oh nevermind, I read the info graphic on part 2 and it addresses this. Essentially if a user goes offline for a few minutes, they'll have to relog back in when they return if the access token is super short. If using refresh tokens along with access tokens, the long-term tokens can't be revoked so same problem.

  • @ZTechSecurity
    @ZTechSecurity Před 3 lety +1

    I searched for this topic because jwt was bugging me.. if you can sign a session ID then they are both same thing in that sense.
    Or if you save jwt to the db it works same as session.
    right?

    • @jgoebel
      @jgoebel  Před 3 lety +3

      in that case you would use a JWT as a session token. So instead of using a random string you would use a JWT. But actually there is no point in using JWT as a session identifier because generating a random session id of sufficient size would be much easier. So would be overengineering imo. The difference is that with JWT you are using cryptography - with a classicial session implementation you don't.

    • @ZTechSecurity
      @ZTechSecurity Před 3 lety

      @@jgoebel how can we protect router with middleware like jwt auth middleware in which we verify the token..

  • @devcaand
    @devcaand Před rokem

    Just came to mind, you can lock user with jwt by not only verifying the secret but also reading their email in that jwt and lock users by maintaining email blacklist. Therefore, you only need to specify 1 email no matter how many new access_tokens would be generated. That would be instantenious lock, as soon as you add that email in the blacklist the "Auth" check will fail.

    • @bekiteshome4670
      @bekiteshome4670 Před rokem

      which is easier to use as a beginner session based or token based authentication?

    • @devcaand
      @devcaand Před rokem

      @@bekiteshome4670 JWT are easier

    • @bekiteshome4670
      @bekiteshome4670 Před rokem

      @@devcaand Ok Thanks

  • @user-bo1cu2fp3z
    @user-bo1cu2fp3z Před 3 lety +3

    You could use encrypted JWT only to store an ID and handle the validity/privileges/user data on redis on the server side, then, no negatives

    • @jgoebel
      @jgoebel  Před 3 lety +3

      yes, but then why the JWT in the first place. If you already have something stateful on the server, you might just use sessions directly. So no need to mess with JWTs

    • @user-bo1cu2fp3z
      @user-bo1cu2fp3z Před 3 lety +2

      I use this case when making APIs that interact with mobile apps, in the case of being only a website I do agree with you, it would be better to use session.

    • @jgoebel
      @jgoebel  Před 3 lety +1

      @@user-bo1cu2fp3z True if you are on mobile as well then this is a different use case. The easiest way would probably be to use OAuth for both web and mobile and on mobile you might get a refresh token for your mobile device as well. And the best thing is that you do not have to implement the token issuing process yourself if use use sth. like login with Apple or login with Google

  • @xenizs9112
    @xenizs9112 Před 3 lety +1

    What approach can you use when you have a SPA hosted on a different domain? as far as I know it's really hard to share cookies cross domain, and some browsers block cross domain cookies by default

    • @jgoebel
      @jgoebel  Před 3 lety +1

      Hi Xenizs, for the browser to share cookies with a cross origin, you need to return a CORS header that is not *, the server needs to send the Access-Control-Allow-Credentials header and you need to configure the REST call on the client side (typically there is a withCredentials options on every library that makes REST calls on the frontend)

    • @xenizs9112
      @xenizs9112 Před 3 lety

      @@jgoebel I know you can set those CORS headers in order for it to work but, I've read that even tho you can, some browsers just don't allow cross domain cookies, so it's just not a recomendable solution.

    • @jgoebel
      @jgoebel  Před 3 lety

      @@xenizs9112 Since all of this relies on CORS, I suppose it would have good browser support

    • @xenizs9112
      @xenizs9112 Před 3 lety

      @@jgoebel I did some research and, I can confirm that even my browser blocks cross origins cookies by default. so it's not a viable solution.

    • @jgoebel
      @jgoebel  Před 3 lety

      @@xenizs9112 cross site cookies work if you have a CORS header that is not * and if you send the Access-Control-With-Credentials from the server and you set the withCredentials option on the frontend. Per default the browser blocks them for security reasons

  • @patrickpan5273
    @patrickpan5273 Před 2 lety

    hi, i just wonder how the implementation is going to be if we are using JWT with cookie for SPA since you said JS cannot access the cookie. How do JWT be sent along with each request when js cannot access it?

    • @jgoebel
      @jgoebel  Před 2 lety

      Hi Patrick, the browser automatically sends the cookie in the background

    • @Cognitoman
      @Cognitoman Před rokem

      Yeah if you look inside your request headers in dev tools under “network” on anything that came from the server you will see something that says “cookie” this just stays on your headers with every request you don’t have to worry about doing it yourself the browser will take care of it for you... I was confused about the same thing for a long time... also the cookie has these things called flags, which is basically like options one of the flags is called “HttpOnly” and by default it’s set to false, so for it being false a user or JavaScript can have access to it by saying this “document.cookie” and get acces too all the cookies which can be dangerous, if a hacker is able to execute some code in the web browser. So what yo I do when sending cookies from the backend is to set it to “httpOnly = true”... which will make JavaScript unable to grab the cookie value or know that it even exists. there is 2 other important options and they “same site” which means the cookie can only be accepted or requested from the same domain , meaning the same website and not 3rd party website, and the 2nd is “secure” which means the cookie can only be sent over https connection and not http, this will protect from man in the middle attacks because https is encrypted and http isn’t. Basically same site, httpOnly, and secure will set by your backend. Those are the only 3 flags you should worry about 99% of the time. I hope that helped you. If you have more questions I can help

  • @emyboybeats4330
    @emyboybeats4330 Před 3 lety

    Can you add JWT to cookies on the client ??

    • @jgoebel
      @jgoebel  Před 3 lety +2

      theoretically yes, but this would not make too much sense because to sign the JWT you need a private key or a secret. Since a website is a public client (someone can just inspect the markup, you would not be able to keep the secret of private key safe). That's why the JWT always needs to come from a confidential client (i.e. the server)

  • @emyitegbe3328
    @emyitegbe3328 Před 3 lety

    @productioncoder will sessions work for both spa and mobile. I'm currently working on a project and can't decide if i should use sessions or go with jwt but store it in a cookie( again back to sessions). By the way great video.

    • @jgoebel
      @jgoebel  Před 3 lety +2

      That's a very good question. So this video was more or less only about web. I think if you have a mobile app, you probably also don't want the user to login every time the app is opened. You probably want a "keep signed in" feature. That's why going with sessions would require you to keep the sessions for quite a while. If you don't want that then you could use JWTs - but then again you would have the problem that you cannot log someone out from the server side. You would also not be able to log people out when they reset their password with JWTs. If that is not a problem then you can go with JWTs

    • @emyitegbe3328
      @emyitegbe3328 Před 3 lety

      @@jgoebel thanks for the response. I came up with this design where i will have separate endpoints for logins i.e. for both browser(spa) and mobile. For spa i will store jwt in a cookie and for mobile will send the token via a POST body. This will be a stateful JWT where it will be persisted in Redis. What do you think of this design?

    • @jgoebel
      @jgoebel  Před 3 lety +2

      The goal of JWT is to not need any state on the server side. So you would not need the Redis, because you can just put the info in the JWT.
      I also think that one login endpoint would be sufficient. On the web, you'd just get a cookie and the browser would send along the cookie for every follow-up request and on mobile you can extract the JWT from the cookie from the server's response and store it on the device. Like so the users don't have to login on mobile when they reopen the app as long as the JWT is not expired

    • @emyitegbe3328
      @emyitegbe3328 Před 3 lety

      @@jgoebel that makes sense. The only issue here is i still see here if a user changes their password, i will have to invalidate all JWT that has be assigned to all devices belonging to that user. In this scenario it seems to make sense to keep a reference to all tokens assigned right.

    • @jgoebel
      @jgoebel  Před 3 lety +1

      In case of JWT password change, the flow would be like this:
      1. User enters correct password on the app and gets a long-lived token that is valid for e.g. 5 days
      2. The day after the user resets the password
      3. The token that was issued the day before is still valid for 4 days. So no need for the user to log in again. That is why - as mentioned in the video, the pure JWT-based solution will not pass a banking audit because you cannot log someone out from the server side.
      To log someone out from the server side you need some stateful solution like sessions. But if you want the user to stay logged in you would need to keep the session around. Storing JWTs inside Redis would therefore not make sense because if you go with a stateful solution, you can just use sessions and then you don't need JWTs. So if you need to log out devices from the server side, you need stateful solution. If not then you can just go with JWT inside of a cookie. If you go with a stateful solution anyway, then you don't need JWTs

  • @ratnachaitanya2663
    @ratnachaitanya2663 Před 3 lety

    If iam logged in a website through auth redirect url token in one browser and again if iam logged in the same website in another browser, it creates another different url token for login . Then which url token will be registerd or tracked by that website ? either First one or next one..?? Thankyou for ur valuable answer in advance..!!

    • @jgoebel
      @jgoebel  Před 3 lety

      JWTs are not stored, they are always validated on the fly. So the server does not store anything about that token but validates the token's signature for every request you make. In that case - since both tokens are valid - you use the application on both browsers

    • @ratnachaitanya2663
      @ratnachaitanya2663 Před 3 lety

      Got it...!!
      Thankyou sir..!!👍

  • @AbdelhameedG
    @AbdelhameedG Před 4 lety

    Good explanation thanks, but what's trending nowadays in the industry ? i can't figure that out, i know that a few years back it was JWT

    • @jgoebel
      @jgoebel  Před 4 lety +1

      So for browser to server communication, you'd use sessions with cookies. For server to server communication, people tend to use JWTs of HTTP Basic Auth

    • @AbdelhameedG
      @AbdelhameedG Před 4 lety

      @@jgoebel Aha I see, thanks for clarifying

  • @myxsoul3329
    @myxsoul3329 Před 2 lety +1

    how about using JWT with sessions

    • @jgoebel
      @jgoebel  Před 2 lety +2

      what would the advantage of this be? You would need to manage both the JWT logic and the sessions

  • @abdelrahmanmostafa9489

    using sessions and jwt will make it highly secure

  • @ZTechSecurity
    @ZTechSecurity Před 3 lety

    So the only secure way to use jwt is to save them in db and if you want to lock out a user just delete it from db!??

    • @jgoebel
      @jgoebel  Před 3 lety +3

      yes and in this case you could save the hustle of JWTs and you could have just used sessions because if you save JWT in the db you have a stateful solution

    • @ZTechSecurity
      @ZTechSecurity Před 3 lety +1

      @@jgoebel I was thinking the same thing :)
      Thanks!

  • @andreigatej6704
    @andreigatej6704 Před rokem

    Thank you for the great video!
    I'd be very curious about 2 things:
    - what is the proper way to handle roles with sessions? with JWT, they're simply part of the payload; I guess you'd simply send the roles as part of user's information(which comes as a HTTP response)?
    - is it possible to prevent XSS attacks(e.g. stealing tokens from LS) by using CSP?
    Thanks!

  • @DanishAnton
    @DanishAnton Před 3 lety

    I believe Session Web Tokens are better than Session Cookies. If Session Cookies are implemented, then its vulnerable to CSRF attacks. To protect against it, a unique identifier has to be sent with each with request (aka CSRF token), so you will have all the disadvantages described for JWT. Using Session Cookies DOES NOT protect against XSS attacks, so XSS protection is still required. If you use Session Web Tokens, then only XSS protection is required. Properly implementing Session Cookies is double the work.

    • @jgoebel
      @jgoebel  Před 3 lety +1

      Hi Danish,
      CSRF tokens are only needed if the server that is rendering the HTML is also receiving the API calls (e.g. if you use Mustache or Handlebars with Node). In a SPA setup, your application would make cross origin request to some server that is probably hosted on a subdomain or on a completely different domain. If the origin of the server where you make API calls to and the SPA are different, you can mitigate all CSRF attack vectors with a proper CORS policy (i.e. some concrete value instead of *)
      Yes, XSS needs to be mitigated anyway regardless of which approach you use. One of the most effective ways is a Content Security Policy.
      Regardless on how CSRF and XSS is mitigated, with JWS token as session tokens, it will not be possible to log someone out from the server side or modify a user's permissions instantly without introducing some form of state (you would need to store revoked tokens somewhere).

    • @DanishAnton
      @DanishAnton Před 3 lety +1

      @@jgoebel CORS does not mitigate all CSRF attacks. It limits XMLHttpRequests but form and source request ignore CORS. Also, CORS is only respected by modern browsers. stackoverflow.com/questions/19793695/does-a-proper-cors-setup-prevent-xsrf . Yes, Session Web Tokens will require the same lookup as Session Cookies so no performance penalty or gain. With Session Web Tokens, setting up CSP and other similar measures (ie sanitize inputs, etc) is all that needs to be focused on. With Session Cookies in a site that uses any Javascript, you would need both XSS and CRSF protection. Session Web Tokens would also save bandwidth since only the Session Web Token would be sent while the CRSF token and Cookie would need to be sent with each HTTP request for Session Cookie auth.

    • @jgoebel
      @jgoebel  Před 3 lety

      @@DanishAnton You can block cross origin requests by checking the Origin header which is sent along to all Cross Origin requests: developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
      In addition the SameSite attribute of the cookie will make sure that the cookie is not sent with source requests or when loading images or something like that. SameSite could also be set to Strict although this has a few usability implications.
      The main is question imo is also if there is completely client-side rendered application like create-react-app how is it supposed to do CSRF tokens because the token would need to be put in the HTML on the initial render, but the application is rendered completely on the client side

    • @DanishAnton
      @DanishAnton Před 3 lety

      @@jgoebel Correction: XSS attacks can occur on any site that uses HTML Posts, including non-JS websites. When I first read what a CSRF token was, I thought isn't this a JWT? As far as a I can tell, a JWT is a more advance CSRF token. Thus I reasoned, if a JWT is used to protect a Cookie Auth implementation, what advantage is gained with Cookie Auth that JWT doesn't already provide. Cookie Auth hampers XSS attacks but doesn't stop or block them. With a successful XSS attack, its easy to gain auth creds. Only CSP, other browser based restrictions, and input sanitation protect against XSS attacks.
      In regards to your CSRF question on create-react-app, its only relevant to set/use CSRF when you are performing auth / auth services.

  • @Joker200084
    @Joker200084 Před 3 lety +1

    Nice! Subscribed... =P

  • @ImDino
    @ImDino Před 2 lety

    are you not using darkmode? You might wanna consider not blinding your viewers.

    • @jgoebel
      @jgoebel  Před 2 lety

      I usually have it turned to auto. But yeah maybe I should always dark mode

  • @ahassan5
    @ahassan5 Před 2 lety

    1. Encrypt data using JWT
    2. Encrypt JWT using session
    3. Store encrypted session using cookie
    U can do it like that

    • @jgoebel
      @jgoebel  Před 2 lety +2

      What added value would it have to use JWTs and sessions together? If you have a server-side state, then you do not need the JWT as part of the session because the session is stored on the server-side anyway

  • @URKI3221
    @URKI3221 Před 2 lety

    how can we integrated Ajax requests with sessions?. I think many developers use JWT because of ajax request to make dinamic web sites, as you know, refresh data without pressing F5. ajax is an insecure approach from my experience.

  • @engespress
    @engespress Před 3 lety +2

    IMO, based on this and other sources I've read, I think sessions (cookies) is better than JWT. JWT are not safe.

    • @jgoebel
      @jgoebel  Před 3 lety +1

      Yes, JWTs are probably not the best thing when it comes to session. However, in general JWTs are very useful for one time access tokens or for implementing E2E encryption.

  • @Meleeman011
    @Meleeman011 Před 3 lety

    rsa is strong lolol.

  • @onepunchman8721
    @onepunchman8721 Před rokem

    good video just too sad that the JWT train is so strong that every lib and framework are JWT first and using sessions is seen as too much work

  • @ahassan5
    @ahassan5 Před 2 lety

    Lol if you are serious, use cookies, sessions and JWTs - for really secure systems. F what they say.

  • @Minefortress21
    @Minefortress21 Před 2 lety +2

    I agree with the points in your video but I think it can still be seen as a bit misleading. YOU DONT STORE JWT in local storage.
    And you DO have access to your COOKIES
    I have read the best practices document that you showed in the video and it does point out how poorly implemented JWT libraries were exploited.
    First of all, these days most JWT implementations have a refresh token and an access token. This solves the problem of logging users out.
    Also JWT is better against CSRF because if you use this method, refresh token will be put in the cookie and the access token will be in memory (js variable). In this situation, if you are a victim of a CSRF attack, the server will reject the request because the refresh token will be sent in the cookie (and not the access token), but the CSRF attack wont be able to access the token from memory.
    There also more ways of logging out users using state based solutions
    and yes JWT is intended for scale and state is easier for JWT-based implementations to handle when you have large number of users than if you were using sessions.
    Also, for the document you shared, the solution to the header changing problem is, you have the JWT signed meaning, you cant edit it.
    Second, you should never allow "none" as the secret alg (algorithm) in the header, and you can hardcode/specify the algorithm to make sure they dont attempt to modify the header.
    Also, JWT tokens are visible but they don't contain private data, and they can be encrypted.
    Also, if your authentication server goes down, you should disable user interaction with your application anyways
    EDIT #1:
    I would like to add that
    you are right about the database becoming the bottleneck before the sessions
    however, that is only applicable if you are on a monolithic or single server infrastructure
    Managing sessions becomes much more difficult when it comes to a microservice or service oriented architecture
    In that situation, either you would need all services to make API calls to your Authentication service which would then become a bottleneck and create a single point of failure
    or
    You would have to implement authentication logic in all your services
    which is duplication or code, and then your session database will max out.
    This gets even worse when you horizontally scale your architecture, by spinning up more services or in different regions