MERN Authentication Tutorial #6 - Signing Tokens

Net Ninja · Intermediate ·🔧 Backend Engineering ·4y ago

Key Takeaways

This video demonstrates how to create and sign JSON Web Tokens (JWT) in a MERN authentication system, using the Json Web Token package to generate and verify tokens, and environment variables to store secret keys.

Full Transcript

all right then so now hopefully you know a little bit more about what Json web tokens are next we need to create them on the server so we can send them back to the browser as part of the response now we want to do that in two places in our API first in the sign up controller function once a user successfully signs up because normally when you sign up to a website you're automatically logged in or authenticated straight away so we want to send a token back in this case and then also in the login controller function after the user successfully logs in now we've not done any of the login logic yet so we'll come back to that later but we have already done all of the sign up logic so far to save users to the database so we can send a token back to the user in this response right here now in order to do that we first need to generate a token and to do that we need to use the Json web token package so let's open up a terminal and make sure you're in the backend folder and then cancel out of the current node process and then we need to type npm install Json web token all one word no spaces and press enter so once that's installed we need to require it at the top so I'm going to say const JWT is equal to require and then we want the Json web token package all right and now on this we can use a method called sign to basically create and sign a token now before we do that down here I'm going to actually create my own function called create token we set that equal to a function and the reason I'm doing this is so we can reuse this function which is going to generate these tokens for us in the login user controller function and the sign up user controller function all right so as an argument I'm going to take in the ID and I'm going to call it underscore ID because that's what mongodb cost the ID property and I just want to kind of keep it the same as that you can just call it ID if you prefer but I'm going to use underscore ID and the reason we're passing this in as an argument is because that is going to be part of the payload of the token all right so how do we create this token well we take the JWT package that we just grabbed right here and we use a method called sign and then inside the sign method we pass in three arguments the first one is an object which kind of represents the payload on the token we want to create so it has different properties and values that are going to be inside the payload now I want an underscore ID property which is equal to the underscore ID that we take in right here now since these are named the same I can just shorten this so that is the first argument you can put other things in here if you want into the payload but remember nothing sensitive and the second argument is going to be the secret remember that is some kind of secret string only known to the server so I could type it in all here but remember if I then upload this to GitHub or some other public repository then people can see this and it should be secret so instead what I'm going to do is I'm going to put this in my environment variables so I'm going to come down here and create a new environment variable called secret and this secret I'm going to copy from my repo ironically and it's just a lot of random words mushed together but to be honest you're probably better go into some kind of password generator you know making something a bit more secure but anyway we have this secret string now and then I can access that from this file by using process.env so I can see right here as a second argument process dot EnV dot secret awesome so that's the second argument the third argument is going to be basically just some options and the only option I want to set is the expires in property and that's going to be three days so basically the user would remain logged in for three days and then the token is going to expire okay and that's all we need to do we're creating this token now but we're not doing anything with it we need to actually return it from this function and therefore when we call this function it's going to return this token for us all right so we need that token down inside this controller function where we sign up a user so after we've saved them to the database let's create a token right here so I can say const token is equal to create token the function we just created up here and we need to pass in the ID of the user now we get that from this user object right here this represents the document we just saved so I can say user dot underscore ID so we're passing that in now and that's going to be on the payload of the token itself now finally I want to pass this token back as a response and we'll do that instead of the user document right here so I'll say token like so and we're passing that back to the browser now and remember this is going to be that big long string or rather those three separate strings bunched together the payload encoded the headers encoded and also the secret encoded all bunched together so let's try this out in Postman all right then so in Postman I've still got the same end point right here we're going to send a post request to that end point and I'm going to use the same data as before just to see that we get the right error back so let's send this and we can see yeah the email is already in use so let's think of another character Luigi so Luigi at netninja.dev same password and we'll send this and yeah we can see now we created that user here's the email address and here my friends is the token and you can see these three dots these are separating the three different parts of the token so we have the first part the header then we have the payload until the next dot which is right here and then finally the signature right there so now on that sign up request we are saving the user to the database we're hashing their password and we also generated a token for that user to send back to the browser to say hey look yeah that was a success and now you authenticated you're automatically logged in after signing up so we're going to use this in the front end later on but first of all for now what I'd like to do is show you how we can log in users as well

Original Description

In this MERN Authentication tutorial, we'll see how to sign tokens and send them back to the client. ⭐⭐ Get the full course now (without ads) on the Net Ninja Pro site: https://netninja.dev/p/mern-auth-tutorial/ ⭐⭐ Get access to all free & PREMIUM courses on Net Ninja Pro: https://net-ninja-pro.teachable.com/p/net-ninja-pro/ 🐱‍💻 Access the course files on GitHub: https://github.com/iamshaunjp/MERN-Auth-Tutorial 🐱‍💻 MERN Stack Tutorial: On Net Ninja Pro - https://www.youtube.com/watch?v=2liZ3uvO9bs On YouTube - https://www.youtube.com/watch?v=98BzS5Oz5E4&list=PL4cUxeGkcC9iJ_KkrkBZWZRHVwnzLIoUE 🐱‍💻 React Tutorial: On Net Ninja Pro - https://codinginpublic.dev/projects/parallax-landing-page/ On YouTube - https://www.youtube.com/watch?v=j942wKiXFu8&list=PL4cUxeGkcC9gZD-Tvwfod2gaISzfRiP9d 🔥🔥🔥 Other resources: VS Code - https://code.visualstudio.com/ MongoDB Atlas - https://code.visualstudio.com/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Net Ninja · Net Ninja · 0 of 60

← Previous Next →
1 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

This video teaches how to create and sign JSON Web Tokens in a MERN authentication system, and how to use environment variables to store secret keys. The viewer will learn how to implement token-based authentication in a MERN system, and how to use the Json Web Token package to generate and verify tokens.

Key Takeaways
  1. Install the Json Web Token package using npm
  2. Require the Json Web Token package in your Node.js file
  3. Create a function to generate and sign tokens
  4. Use environment variables to store secret keys
  5. Implement token signing in your MERN authentication system
  6. Test token signing using Postman
💡 Using environment variables to store secret keys is a good practice to keep your secret keys secure.

Related Reads

Up next
/dev/push: An Open Vercel Alternative to Ship Your Apps Quickly
Ian Wootten
Watch →