Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Nest.js: A Progressive Node.js Framework

You're reading from   Nest.js: A Progressive Node.js Framework Hit the ground running with Nest.js

Arrow left icon
Product type Paperback
Published in Nov 2019
Publisher Packt
ISBN-13 9781800204737
Length 317 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (6):
Arrow left icon
Greg Magolan Greg Magolan
Author Profile Icon Greg Magolan
Greg Magolan
Patrick Housley Patrick Housley
Author Profile Icon Patrick Housley
Patrick Housley
Backstop Media LLC Backstop Media LLC
Author Profile Icon Backstop Media LLC
Backstop Media LLC
Adrien de Peretti Adrien de Peretti
Author Profile Icon Adrien de Peretti
Adrien de Peretti
Jay Bell Jay Bell
Author Profile Icon Jay Bell
Jay Bell
David Guijarro David Guijarro
Author Profile Icon David Guijarro
David Guijarro
+2 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface
1. Introduction FREE CHAPTER 2. Overview 3. Nest.js authentication 4. Dependency Injection system of Nest.js 5. TypeORM 6. Sequelize 7. Mongoose 8. Web sockets 9. Microservices 10. Routing and request handling in Nest.js 11. OpenAPI (Swagger) Specification 12. Command Query Responsibility Separation (CQRS) 13. Architecture 14. Testing 15. Server-side Rendering with Angular Universal

Authentication

Authentication is one of the most important aspects of developing. As developers, we always want to make sure that users can only access the resources they have permission to access. Authentication can take many forms, from showing your drivers license or passport to providing a username and password for a login portal. In recent years these authentication methods have expanded out to become more complicated, but we still need the same server-side logic to make sure that these authenticated users are always who they say they are and persist this authentication so they do not need to reauthenticate for every single call to a REST API or Websocket because that would provide a pretty terrible user experience. The chosen library for this is ironically named Passport as well, and is very well known and used in the Node.js ecosystem. When integrated into Nest it uses a JWT (JSON Web Token) strategy. Passport is a Middleware that the HTTP call is passed through before hitting the endpoint at the controller. This is the AuthenticationMiddleware written for the example project that extends NestMiddleware, authenticating each user based on the email in the request payload.

@Injectable()  
export class AuthenticationMiddleware implements NestMiddleware {  
   constructor(private userService: UserService) { }  

   async resolve(strategy: string): Promise<ExpressMiddleware> {  
       return async (req, res, next) => {  
           return passport.authenticate(strategy, async (/*...*/args: any[]) => {  
               const [, payload, err] = args;  
                if (err) {  
                    return res.status(HttpStatus.BAD_REQUEST).send('Unable to authenticate the user.');  
                }  

               const user = await this.userService.findOne({
                    where: { email: payload.email }
               });  
                req.user = user;  
                return next();  
            })(req, res, next);  
        };  
    }  
}

Nest also implements Guards, which are decoratorated with the same @Injectable() as other providers. Guards restrict certain endpoints based on what the authenticated user has access to. Guards will be discussed more in the Authentication chapter.

You have been reading a chapter from
Nest.js: A Progressive Node.js Framework
Published in: Nov 2019
Publisher: Packt
ISBN-13: 9781800204737
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime