From the course: Mastering Nest.js: Build Scalable Applications with Mastery in Nest.js Framework

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Authentication and authorization

Authentication and authorization

When building backend applications, we often want to protect the routes in our application so that only authorized data can use or call the endpoints. And with the help of NestJS interceptors, we can easily create auth functionality and check for the users. So let's implement the auth functionality in the current example. I'll create a separate interceptor naming it as auth. Now inside the auth interceptor, I'll first get the context of request object by giving switch to HTTP method dot get request. And we'll assign the authorization headers to a token constant. Then an if condition to validate the token that if token does not exist, throw a new unauthorized exception, missing authorization token. Now we are going to use the password as token value. So first we need to retrieve the user ID from params. I'll create a constant named user ID and assign the request dot params dot ID. Now we are going to pass their user ID to the find one method of user service. So let me inject the user…

Contents