MERN Authentication Tutorial #6 - Signing Tokens
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
GraphQL Tutorial #5 - Express App Setup
Net Ninja
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
GraphQL Tutorial #8 - Root Query
Net Ninja
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
GraphQL Tutorial #12 - Author Type
Net Ninja
GraphQL Tutorial #13 - Type Relations
Net Ninja
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
GraphQL Tutorial #18 - Mutations
Net Ninja
GraphQL Tutorial #19 - More on Mutations
Net Ninja
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
GraphQL Tutorial #23 - Create React App
Net Ninja
GraphQL Tutorial #24 - Book List Component
Net Ninja
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
GraphQL Tutorial #28 - Add Book Component
Net Ninja
GraphQL Tutorial #29 - External Query File
Net Ninja
GraphQL Tutorial #30 - Updating Component State
Net Ninja
GraphQL Tutorial #31 - Composing Queries
Net Ninja
GraphQL Tutorial #32 - query variables
Net Ninja
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
GraphQL Tutorial #34 - Book Details Component
Net Ninja
GraphQL Tutorial #36 - Styling the App
Net Ninja
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
Updated Vue & Firebase Course (Udemy)
Net Ninja
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja
More on: LLM Engineering
View skill →Related Reads
📰
📰
📰
📰
Flask: The Python Web Framework That Every Developer Should Learn
Medium · Python
Swift typealias — What It Is, What It Does, and Why It Matters
Medium · Programming
s3fifo 1.0: Zero-Allocation S3-FIFO Cache for Node.js is Ready for Production
Dev.to · JeongSeop Byeon
Node.js Error Handling Patterns for Production Queue Systems
Dev.to · Faisal Nadeem
🎓
Tutor Explanation
DeepCamp AI