
Lesson Description
The "Authentication Middleware" Lesson is part of the full, API Design in Node.js, v5 course featured in this preview video. Here's what you'd learn in this lesson:
Scott demonstrates creating and authentication middleware that checks for a bearer token, verifies it, and attaches the user to the request object, using TypeScript for typing.
Transcript from the "Authentication Middleware" Lesson
[00:00:00]
>> Speaker 1: Now we need to make some authentication middleware so that we can use it on any route, or set of routes, or globally wherever we want to lock down access We're going to make an authentication middleware that checks for all of this, so let's go to our middleware and create a new one called auth
[00:00:00]
We'll import some types: requests, response, and the next function We'll import verify token and get that type We can create an interface called AuthenticatedRequest, which essentially extends the request from Express
[00:00:00]
When we authenticate and get the user, we'll attach the user to the request object and pass it along This type allows us to have a user attached to the request When you're in your controllers, you can do `req.user` and see a user that is properly typed
[00:00:00]
This is optional and just helps with TypeScript type definitions Let's create the route for authenticate token This is a middleware that will take a request, response, and next function
[00:00:00]
We'll use a try-catch block to prevent server crashes The strategy is to:
1 Check the Authorization header for a bearer token
2 Get the actual JWT from that value
3 Verify the token
4
[00:00:00]
If verified, attach the user to the request
5 Call next()
6 If anything breaks, deny access
First, we'll get the auth header using `req.headers` and look for the Authorization header
[00:00:00]
We'll split the header to extract the token because a bearer token comes as "Bearer [token]" If no token is present, we'll return a bad request status, indicating the client didn't provide authentication
[00:00:00]
If a token exists, we'll verify it using `verifyToken()` If successful, we'll attach the payload to `req.user` If verification fails, we'll return a 403 Forbidden status
[00:00:00]
Finally, we'll call `next()` to continue the request flow By using the AuthenticatedRequest interface, we resolve any TypeScript typing concerns around the user property.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops