Logo

    Hasty Treat - Authentication: LocalStorage vs Cookies vs Sessions vs Tokens

    enMarch 04, 2019
    What are the main techniques for user session management?
    How do cookies and local storage differ in data storage?
    What is the purpose of LogRocket in web development?
    What security vulnerabilities affect JWTs and sessions?
    How can developers protect against CSRF attacks?

    • Understanding Authentication Techniques: Local Storage, Cookies, Sessions, and TokensAuthentication is crucial in web development, and techniques like local storage, cookies, sessions, and tokens help manage user sessions and data. Understand their differences to make informed decisions. LogRocket offers session replays, network requests, Redux store access, and console errors or logs to enhance debugging.

      Authentication, cookies, sessions, and tokens are not mutually exclusive but rather different techniques used in web development for managing user sessions and data. In this episode of Syntax, Wes, Barracuda, Boss, and Scott El Toro Loco discussed the ins and outs of these technologies. Authentication is a crucial aspect of web development, and the panelists explained various methods for implementing it, including local storage, cookies, sessions, and tokens. While local storage and cookies store data on the client-side, sessions and tokens handle server-side authentication. The episode was sponsored by LogRocket, a service that provides full visibility into bugs on websites. LogRocket offers session replays, network requests, Redux store access, and console errors or logs, allowing developers to understand the user experience and diagnose issues more effectively. To summarize, authentication is an essential part of web development, and developers must understand the differences between local storage, cookies, sessions, and tokens to make informed decisions on which technique to use in specific situations. Additionally, tools like LogRocket can significantly enhance the debugging process by providing comprehensive visibility into user interactions and website behavior.

    • Understanding User Tracking with JWT and SessionsAs a front end developer, it's essential to know how to track users using JWT or sessions and identify users on requests using cookies or local storage for secure and efficient web applications.

      As a front end developer, it's essential to understand how user authentication and tracking work in web applications. Two common methods for tracking users are JSON Web Tokens (JWT) and sessions. When signing into a web application, the server returns a JWT or a session ID. JWT is a seemingly random token that contains a user ID and can be stored in local storage or a cookie. Upon every request, the token must be sent along for authentication. The cookie-based approach also involves logging into a website and receiving a successful or unsuccessful response. In this case, a cookie with a session ID is set, and it identifies the user on the server for subsequent requests. Understanding which method to use depends on factors like security, performance, and user experience. JWT offers better security since the token is sent with every request, while sessions can be more efficient since the server maintains the session state. In summary, as a front end developer, it's crucial to know how to track users using JWT or sessions and identify users on requests using cookies or local storage. This knowledge will enable you to build secure and efficient web applications.

    • Token-based vs Session-based AuthenticationBoth token-based and session-based authentication have their pros and cons. Token-based is stateless, easy to use in non-website apps, but hard to expire. Session-based is stateful, easy to expire, but can be a challenge to maintain across server restarts.

      When it comes to authentication methods, both token-based and session-based have their unique advantages and disadvantages. Token-based authentication, which includes JSON Web Tokens (JWT), is stateless and does not require maintaining a list of logged-in users on the back end server. This makes it ideal for deploying websites and microservices across multiple servers or domain names. Tokens can also store data like user ID or preferences, and are easy to use in non-website applications such as mobile apps. However, the downside is that it's difficult to expire tokens, requiring the use of blacklists or algorithm changes to log users out. On the other hand, session-based authentication, popular with server-rendered applications, is stateful and requires maintaining a list of session IDs. While it allows for easy expiration and logging out of users, it can be a challenge to maintain sessions across server restarts, requiring the use of databases or adapters to store and manage sessions. Ultimately, the choice between token-based and session-based authentication depends on the specific use case and requirements of the application.

    • Advantages of Sessions and Cookies over Local StorageSessions and cookies offer faster, seamless first render, are suitable for server-side rendering, and provide a more secure approach to handling user authentication and session management compared to local storage.

      Sessions and cookie-based approaches offer several advantages over local storage when it comes to tracking user information and rendering UI in web applications. Sessions allow for a passive, cookie-based approach where the cookie is automatically sent along with each request to the server, enabling a faster and more seamless first render. In contrast, local storage requires the token to be actively pulled out and sent with each request, leading to potential delays and a less optimal user experience. Moreover, when it comes to server-side rendering (SSR), cookies are the only viable option as they can be automatically sent to the server with each request, allowing for SSR of authenticated components. Local storage, on the other hand, cannot be sent to the server on every request, making it unsuitable for SSR. Another consideration is security. While there are debates on both sides, it's important to note that cookies can be vulnerable to session hijacking and other attacks if not properly secured. JSON Web Tokens (JWTs) offer an alternative, more secure approach to handling user authentication and session management. In summary, sessions and cookie-based approaches offer several advantages over local storage when it comes to tracking user information, rendering UI, and implementing server-side rendering. While there are trade-offs and considerations, such as security, the passive and implicit nature of cookies make them a popular choice for many web applications.

    • JWTs and sessions: Different security vulnerabilitiesJWTs are susceptible to XSS attacks, while sessions can fall victim to CSRF attacks. Developers must sanitize user inputs and implement unique tokens to secure their applications.

      Both JSON Web Tokens (JWT) and sessions have their own security vulnerabilities that developers need to be aware of. JWTs are susceptible to Cross-Site Scripting (XSS) attacks, which allow an attacker to steal a user's token and make unauthorized requests on their behalf. To prevent XSS attacks, developers must ensure they sanitize user inputs and avoid injecting unsanitized HTML into their webpages. On the other hand, sessions can fall victim to Cross-Site Request Forgery (CSRF) attacks, where an attacker can trick a user into making a malicious request on their behalf, leading to unintended actions. To protect against CSRF attacks, developers can implement unique tokens that are included in hidden form fields and verified on the server-side before processing requests. Both JWTs and sessions have their strengths and weaknesses, and the choice between them depends on the specific use case and security requirements. It's essential for developers to understand these vulnerabilities and take appropriate measures to secure their applications. Watching YouTube videos and learning about these attack vectors can help developers make informed decisions and implement effective countermeasures.

    • Managing Authentication in React ApplicationsTraditional back ends often use sessions, while modern setups may use JSON Web Tokens. Both methods use cookies for server-rendered applications. Consider using services like Auth0, Passport JS, or Netlify's Identity Auth Platform for assistance.

      When building a React application with a custom back end or using an external back end, authentication methods can vary between using sessions and JSON Web Tokens. Traditional back ends often use sessions, while modern setups may use JSON Web Tokens. Both methods use cookies instead of local storage for server-rendered applications. If managing authentication feels overwhelming, consider using services like Auth0, Passport JS, or Netlify's Identity Auth Platform. These services offer varying levels of assistance, with some handling everything for you and others just generating tokens or sessions. The choice depends on your specific requirements and comfort level. Tweet us @syntaxfm with any questions or comments. Thanks for listening, and join us on Wednesday for more Syntax! For the full archive and to subscribe, visit syntax.fm.

    Was this summary helpful?

    Recent Episodes from Syntax - Tasty Web Development Treats

    824: Taylor Otwell's opinions on PHP, React, Laravel and Lamborghini Memes

    824: Taylor Otwell's opinions on PHP, React, Laravel and Lamborghini Memes

    In this episode of Syntax, Wes and Scott talk with Taylor Otwell, the creator of Laravel. Taylor shares insights on his journey from creating Laravel in his free time to building a strong community and user base. He discusses Laravel’s growth, including the major features and tools that were developed over the years. Taylor also shares his outlook on the PHP ecosystem, productivity tips, and plans for Laravel Cloud, a new deployment platform for PHP and Laravel applications.

    Show Notes

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    823: Is Cursor AI the VS Code Killer?

    823: Is Cursor AI the VS Code Killer?

    Scott and Wes serve up a discussion on AI coding assistants with a deep look at Cursor AI, exploring its unique features like multi-line auto-complete and Smart Rewrites. They also discuss why Cursor’s intuitive UI stands out and tackle the big question: is it worth the investment?

    Show Notes

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    822: Receipt Printer with JavaScript

    822: Receipt Printer with JavaScript

    Wes unveils his Hack-Week project —a thermal printer controlled by JavaScript that prints out Sentry.io errors in real-time. Scott and Wes dive into the nitty-gritty of how it works, from the ESC/POS protocol to tackling socket issues, and whether the project was worth the effort.

    Show Notes

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    821: Is Tauri the Electron Killer?

    821: Is Tauri the Electron Killer?

    In this episode of Syntax, Wes and Scott talk with Daniel Thompson-Yvetot about Tauri. They dive into what Tauri is, the motivations behind its development, its open-source ecosystem, use cases, and more.

    Show Notes

    Links

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    820: Potluck: 8000 ESLint Errors × HTML Time Tag × 7 Meg React Bundle × CSS Modules

    820: Potluck: 8000 ESLint Errors × HTML Time Tag × 7 Meg React Bundle × CSS Modules

    In this Potluck episode of Syntax, Scott and Wes answer your questions, from weighing the trade-offs between numerous small npm packages and a few larger ones to managing the challenges of work-from-home life. They also explore CSS modules, strategies for shrinking JavaScript bundles, and even where to find the best replacement ear cups for your headphones.

    Show Notes

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    819: Fun & Profitable Side Projects for Developers

    819: Fun & Profitable Side Projects for Developers

    Scott and Wes serve up a hasty discussion on side projects, sharing their latest Hack Week experiments and tips on how to turn fun ideas into profitable ventures. They cover everything from finding inspiration to choosing the right tech, and even offer advice on how to finish what you start.

    Show Notes

    • 00:00 Welcome to Syntax!
    • 01:11 Brought to you by Sentry.io.
    • 01:27 Wes’ Hack Week project.
    • 02:30 Scott’s Hack Week project.
    • 04:18 Where do you get ideas for side projects?
    • 09:22 End goals for a side project.
    • 14:47 Other end goals.
    • 16:45 What tech should you use?
    • 20:34 Keeping notes.
    • 23:14 Finishing side projects.
    • 26:39 Shameless Plugisode!

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    818: CJ × Hosting Meetups - Lunch and Learn

    818: CJ × Hosting Meetups - Lunch and Learn

    In this episode of Syntax, Wes and Scott talk with CJ Reynolds about the resurgence of meetups in a post-COVID world. They discuss the benefits of attending and speaking at meetups, and the logistics of organizing them. CJ also shares his experiences running the DenverScript meetup, including sourcing speakers, finding venues, and ensuring a welcoming community.

    Show Notes

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    817: You Need These 30 Apps - PART 1

    817: You Need These 30 Apps - PART 1

    Scott and Wes kick off part 1 of a 2-part series, breaking down 30 must-have apps for web developers and productivity enthusiasts. From file management tools to media utilities, they cover everything you need to supercharge your workflow.

    Show Notes

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    816: Why Your CSS Sucks

    816: Why Your CSS Sucks

    Scott and Wes break down why your CSS might suck—from misusing specificity to not leveraging CSS variables. Tune in as they dive into common pitfalls that are making your stylesheets a hot mess.

    Show Notes

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    815: Deno 2 with Ryan Dahl

    815: Deno 2 with Ryan Dahl

    In this episode of Syntax, Wes and Scott talk with Ryan Dahl about Deno 2.0, its new features and use of web standards, and how it seamlessly integrates with popular frameworks like Next.js. Ryan shares insights on the motivations behind Deno’s creation, its emphasis on simplicity and security, and offers his take on the evolving JavaScript ecosystem.

    Show Notes

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    Related Episodes

    How To Build Your Own Auth

    How To Build Your Own Auth

    In this episode of Syntax, Scott and Wes talk about building your own authentication — diving deep into JWT, sessions, tokens, cookies, local storage, CSRF, and how it all works!

    Prismic - Sponsor

    Prismic is a Headless CMS that makes it easy to build website pages as a set of components. Break pages into sections of components using React, Vue, or whatever you like. Make corresponding Slices in Prismic. Start building pages dynamically in minutes. Get started at prismic.io/syntax.

    LogRocket - Sponsor

    LogRocket lets you replay what users do on your site, helping you reproduce bugs and fix issues faster. It’s an exception tracker, a session re-player and a performance monitor. Get 14 days free at logrocket.com/syntax.

    Hasura - Sponsor

    With Hasura, you can get a fully managed, production-ready GraphQL API as a service to help you build modern apps faster. You can get started for free in 30 seconds, or if you want to try out the Standard tier for zero cost, use the code “TryHasura” at this link: hasura.info. We’ve also got an amazing selection of GraphQL tutorials at hasura.io/learn.

    Show Notes

    01:51 - Overview

    05:13 - JWT

    • Base 64 encoded (not encrypted) token that contains data. We have both accessTokens and refreshTokens.
    • JWT has three parts:
      • Header
        • What kind of algo was used
      • Payload
        • Data about the user
        • Email
        • Username
        • UserID
        • refreshToken, authToken, sessionId
      • Signature
        • This ensures that no one monkeyed with the above parts. If you change your email in the payload, the signature is not invalid, because in order to generate the signature, it uses the header and payload as part of it.
    • accessToken
      • A short lived JWT that contains the sessionTokenuserId and expires after 90min.
    • refreshToken
      • A long lived JWT that contains just the sessionToken and doesn’t expire.
    • JWT can be decoded and read, but you have to encode them with your secret.
    • JWT can be stored anywhere, there are two main places:

    20:26 - Cookies

    • We use httpOnly, secure cookies to store the accessToken and the refreshToken. The accessToken is a session cookie and is removed whenever the browser is closed. The refreshToken is valid for 100 days but is also re-created and revalidated for 100 more days each time the accessToken is generated.
    • Because these are httpOnly cookies, they cannot be accessed by JavaScript in the client and can only be set and removed on the server.
    • Note: Safari has stricter rules than others for same domain cookies (e.g. localhost won’t work).

    34:26 - Sessions

    • Sessions are when a user logs in on a device. If you open a phone and log in and a computer and log in, those will create two different sessions. A session contains information about the user’s connection (like their IP) but it also contains the userId which allows us to create new accessTokens from a valid session.
    • Sessions can be valid or invalid. This allows us to log anyone out by setting their session to valid: false.
    • Sessions also have sessionToken which are generated on authentication or create account.

    38:10 - CORS

    • Cross-origin-resource-sharing
    • Can be super tricky to get working cross-domain
    • You usually have to actually visit the website for the cookie to be set, even with lax cors

    46:06 - CSRF

    48:47 - Authentication process

    52:13 - Helper Packages

    Links

    ××× SIIIIICK ××× PIIIICKS ×××

    Shameless Plugs

    Tweet us your tasty treats!

    TPDP015: Authorizing Access with OAuth

    TPDP015: Authorizing Access with OAuth
    In this episode I am joined by Ryan Chenkie, Developer Advocate at the internet safety company, Auth0. Ryan and I discuss OAuth and how it can be used for authorizing third-party access to your data. If you've been keeping up, you'll remember that I wrote the very popular ng-cordova-oauth and ng2-cordova-oauth libraries for Ionic Framework that allowed mobile applications to work with OAuth providers like Google and Facebook. There are a lot of common questions around the protocol such as storing tokens, refreshing tokens, and implementing OAuth logic within code. The goal in this episode is to clear up the common questions and give everyone a better understanding on how OAuth works as well as the best practicies. A writeup to this episode can be found via https://www.thepolyglotdeveloper.com/2017/08/tpdp-e15-authorizing-access-oauth/

    Supper Club × Open Table LIVE SHOW

    Supper Club × Open Table LIVE SHOW

    In this supper club episode of Syntax, Wes and Scott recorded a live open table episode with guests calling in to talk about Wasm, building Riverside.fm, home networking, getting a job at Microsoft, Svelte and Sveltekit, htmx, and more!

    Auth0 - Sponsor

    Auth0 is the easiest way for developers to add authentication and secure their applications. They provides features like user management, multi-factor authentication, and you can even enable users to login with device biometrics with something like their fingerprint. Not to mention, Auth0 has SDKs for your favorite frameworks like React, Next.js, and Node/Express. Make sure to sign up for a free account and give Auth0 a try with the link below. https://a0.to/syntax

    Appwrite - Sponsor

    Appwrite is a self-hosted backend-as-a-service platform that provides developers with all the core APIs required to build any application. Get free cloud credits by signing up for early access to the Appwrite Cloud launch!

    Show Notes

    Tweet us your tasty treats

    #2 - Die Illusion der Zustimmung - Teil 1

    #2 - Die Illusion der Zustimmung - Teil 1
    Wir wollen entscheiden, mit wem wir unsere privaten Informationen teilen. Im digitalen Alltag wissen wir allerdings häufig nicht, was wir alles preisgeben. Denken wir etwa an eine Google Suchanfrage, oder die Informationen die unsere Handys täglich versenden. Wir wissen oft nicht genug, um uns wirklich zu entscheiden. Eine (absichtliche?) Informationsflut wie in Datenschutzbestimmungen mit mehr als 30 000 Wörtern hilft hier auch nicht weiter. Stellen wir uns die Frage: Können wir wirklich entscheiden mit wem wir unsere Daten teilen, oder ist das nur mehr eine Illusion?
    Logo

    © 2024 Podcastworld. All rights reserved

    Stay up to date

    For any inquiries, please email us at hello@podcastworld.io