- 1. API with NestJS #1. Controllers, routing and the module structure
- 2. API with NestJS #2. Setting up a PostgreSQL database with TypeORM
- 3. API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies
- 4. API with NestJS #4. Error handling and data validation
- 5. API with NestJS #5. Serializing the response with interceptors
- 6. API with NestJS #6. Looking into dependency injection and modules
- 7. API with NestJS #7. Creating relationships with Postgres and TypeORM
- 8. API with NestJS #8. Writing unit tests
- 9. API with NestJS #9. Testing services and controllers with integration tests
- 10. API with NestJS #10. Uploading public files to Amazon S3
- 11. API with NestJS #11. Managing private files with Amazon S3
- 12. API with NestJS #12. Introduction to Elasticsearch
- 13. API with NestJS #13. Implementing refresh tokens using JWT
- 14. API with NestJS #14. Improving performance of our Postgres database with indexes
- 15. API with NestJS #15. Defining transactions with PostgreSQL and TypeORM
- 16. API with NestJS #16. Using the array data type with PostgreSQL and TypeORM
- 17. API with NestJS #17. Offset and keyset pagination with PostgreSQL and TypeORM
- 18. API with NestJS #18. Exploring the idea of microservices
- 19. API with NestJS #19. Using RabbitMQ to communicate with microservices
- 20. API with NestJS #20. Communicating with microservices using the gRPC framework
- 21. API with NestJS #21. An introduction to CQRS
- 22. API with NestJS #22. Storing JSON with PostgreSQL and TypeORM
- 23. API with NestJS #23. Implementing in-memory cache to increase the performance
- 24. API with NestJS #24. Cache with Redis. Running the app in a Node.js cluster
- 25. API with NestJS #25. Sending scheduled emails with cron and Nodemailer
- 26. API with NestJS #26. Real-time chat with WebSockets
- 27. API with NestJS #27. Introduction to GraphQL. Queries, mutations, and authentication
- 28. API with NestJS #28. Dealing in the N + 1 problem in GraphQL
- 29. API with NestJS #29. Real-time updates with GraphQL subscriptions
- 30. API with NestJS #30. Scalar types in GraphQL
- 31. API with NestJS #31. Two-factor authentication
- 32. API with NestJS #32. Introduction to Prisma with PostgreSQL
- 33. API with NestJS #33. Managing PostgreSQL relationships with Prisma
- 34. API with NestJS #34. Handling CPU-intensive tasks with queues
- 35. API with NestJS #35. Using server-side sessions instead of JSON Web Tokens
- 36. API with NestJS #36. Introduction to Stripe with React
- 37. API with NestJS #37. Using Stripe to save credit cards for future use
- 38. API with NestJS #38. Setting up recurring payments via subscriptions with Stripe
- 39. API with NestJS #39. Reacting to Stripe events with webhooks
- 40. API with NestJS #40. Confirming the email address
- 41. API with NestJS #41. Verifying phone numbers and sending SMS messages with Twilio
- 42. API with NestJS #42. Authenticating users with Google
- 43. API with NestJS #43. Introduction to MongoDB
- 44. API with NestJS #44. Implementing relationships with MongoDB
- 45. API with NestJS #45. Virtual properties with MongoDB and Mongoose
- 46. API with NestJS #46. Managing transactions with MongoDB and Mongoose
- 47. API with NestJS #47. Implementing pagination with MongoDB and Mongoose
- 48. API with NestJS #48. Definining indexes with MongoDB and Mongoose
- 49. API with NestJS #49. Updating with PUT and PATCH with MongoDB and Mongoose
- 50. API with NestJS #50. Introduction to logging with the built-in logger and TypeORM
- 51. API with NestJS #51. Health checks with Terminus and Datadog
- 52. API with NestJS #52. Generating documentation with Compodoc and JSDoc
- 53. API with NestJS #53. Implementing soft deletes with PostgreSQL and TypeORM
- 54. API with NestJS #54. Storing files inside a PostgreSQL database
- 55. API with NestJS #55. Uploading files to the server
- 56. API with NestJS #56. Authorization with roles and claims
- 57. API with NestJS #57. Composing classes with the mixin pattern
- 58. API with NestJS #58. Using ETag to implement cache and save bandwidth
- 59. API with NestJS #59. Introduction to a monorepo with Lerna and Yarn workspaces
- 60. API with NestJS #60. The OpenAPI specification and Swagger
- 61. API with NestJS #61. Dealing with circular dependencies
- 62. API with NestJS #62. Introduction to MikroORM with PostgreSQL
- 63. API with NestJS #63. Relationships with PostgreSQL and MikroORM
- 64. API with NestJS #64. Transactions with PostgreSQL and MikroORM
- 65. API with NestJS #65. Implementing soft deletes using MikroORM and filters
- 66. API with NestJS #66. Improving PostgreSQL performance with indexes using MikroORM
- 67. API with NestJS #67. Migrating to TypeORM 0.3
- 68. API with NestJS #68. Interacting with the application through REPL
- 69. API with NestJS #69. Database migrations with TypeORM
- 70. API with NestJS #70. Defining dynamic modules
- 71. API with NestJS #71. Introduction to feature flags
- 72. API with NestJS #72. Working with PostgreSQL using raw SQL queries
- 73. API with NestJS #73. One-to-one relationships with raw SQL queries
- 74. API with NestJS #74. Designing many-to-one relationships using raw SQL queries
- 75. API with NestJS #75. Many-to-many relationships using raw SQL queries
- 76. API with NestJS #76. Working with transactions using raw SQL queries
- 77. API with NestJS #77. Offset and keyset pagination with raw SQL queries
- 78. API with NestJS #78. Generating statistics using aggregate functions in raw SQL
- 79. API with NestJS #79. Implementing searching with pattern matching and raw SQL
- 80. API with NestJS #80. Updating entities with PUT and PATCH using raw SQL queries
- 81. API with NestJS #81. Soft deletes with raw SQL queries
- 82. API with NestJS #82. Introduction to indexes with raw SQL queries
- 83. API with NestJS #83. Text search with tsvector and raw SQL
- 84. API with NestJS #84. Implementing filtering using subqueries with raw SQL
- 85. API with NestJS #85. Defining constraints with raw SQL
- 86. API with NestJS #86. Logging with the built-in logger when using raw SQL
- 87. API with NestJS #87. Writing unit tests in a project with raw SQL
- 88. API with NestJS #88. Testing a project with raw SQL using integration tests
- 89. API with NestJS #89. Replacing Express with Fastify
- 90. API with NestJS #90. Using various types of SQL joins
- 91. API with NestJS #91. Dockerizing a NestJS API with Docker Compose
- 92. API with NestJS #92. Increasing the developer experience with Docker Compose
- 93. API with NestJS #93. Deploying a NestJS app with Amazon ECS and RDS
- 94. API with NestJS #94. Deploying multiple instances on AWS with a load balancer
- 95. API with NestJS #95. CI/CD with Amazon ECS and GitHub Actions
- 96. API with NestJS #96. Running unit tests with CI/CD and GitHub Actions
- 97. API with NestJS #97. Introduction to managing logs with Amazon CloudWatch
- 98. API with NestJS #98. Health checks with Terminus and Amazon ECS
- 99. API with NestJS #99. Scaling the number of application instances with Amazon ECS
- 100. API with NestJS #100. The HTTPS protocol with Route 53 and AWS Certificate Manager
- 101. API with NestJS #101. Managing sensitive data using the AWS Secrets Manager
- 102. API with NestJS #102. Writing unit tests with Prisma
- 103. API with NestJS #103. Integration tests with Prisma
- 104. API with NestJS #104. Writing transactions with Prisma
- 105. API with NestJS #105. Implementing soft deletes with Prisma and middleware
- 106. API with NestJS #106. Improving performance through indexes with Prisma
- 107. API with NestJS #107. Offset and keyset pagination with Prisma
- 108. API with NestJS #108. Date and time with Prisma and PostgreSQL
- 109. API with NestJS #109. Arrays with PostgreSQL and Prisma
- 110. API with NestJS #110. Managing JSON data with PostgreSQL and Prisma
- 111. API with NestJS #111. Constraints with PostgreSQL and Prisma
- 112. API with NestJS #112. Serializing the response with Prisma
- 113. API with NestJS #113. Logging with Prisma
- 114. API with NestJS #114. Modifying data using PUT and PATCH methods with Prisma
- 115. API with NestJS #115. Database migrations with Prisma
- 116. API with NestJS #116. REST API versioning
- 117. API with NestJS #117. CORS – Cross-Origin Resource Sharing
- 118. API with NestJS #118. Uploading and streaming videos
- 119. API with NestJS #119. Type-safe SQL queries with Kysely and PostgreSQL
- 120. API with NestJS #120. One-to-one relationships with the Kysely query builder
- 121. API with NestJS #121. Many-to-one relationships with PostgreSQL and Kysely
While developing our application, security should be one of our main concerns. One of the ways we can improve it is by implementing a two-factor authentication mechanism. This article goes through its principles and puts them into practice with NestJS and Google Authenticator.
Adding two-factor authentication
The core idea behind two-factor authentication is to confirm the user’s identity in two ways. There is an important distinction between two-step authentication and two-factor authentication. A common example is with the ATM. To use it, we need both a credit card and a PIN code. We call it a two-factor authentication because it requires both something we have and something we know. For example, requiring a password and a PIN code could be called a two-step flow instead.
The very first thing is to create a secret key unique for every user. In the past, I’ve used the speakeasy library for that. Unfortunately, it is not maintained anymore. Therefore, in this article, we use the otplib package for this purpose.
1 |
npm install otplib |
Along with the above secret, we also generate a URL with the otpauth:// protocol. It is used by applications such as Google Authenticator. We need to provide a name for our application to display it on our users’ devices. To do that, let’s add an environment variable called TWO_FACTOR_AUTHENTICATION_APP_NAME.
twoFactorAuthentication.service.ts
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 |
import { Injectable } from '@nestjs/common'; import { authenticator } from 'otplib'; import User from '../../users/user.entity'; import { UsersService } from '../../users/users.service'; @Injectable() export class TwoFactorAuthenticationService { constructor ( private readonly usersService: UsersService, private readonly configService: ConfigService ) {} public async generateTwoFactorAuthenticationSecret(user: User) { const secret = authenticator.generateSecret(); const otpauthUrl = authenticator.keyuri(user.email, this.configService.get('TWO_FACTOR_AUTHENTICATION_APP_NAME'), secret); await this.usersService.setTwoFactorAuthenticationSecret(secret, user.id); return { secret, otpauthUrl } } } |
An essential thing above is that we save the generated secret in the database. We will need it later.
user.entity.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'; @Entity() class User { @PrimaryGeneratedColumn() public id: number; @Column({ nullable: true }) public twoFactorAuthenticationSecret?: string; // ... } export default User; |
user.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import User from './user.entity'; @Injectable() export class UsersService { constructor( @InjectRepository(User) private usersRepository: Repository<User>, ) {} async setTwoFactorAuthenticationSecret(secret: string, userId: number) { return this.usersRepository.update(userId, { twoFactorAuthenticationSecret: secret }); } // ... } |
We also need to serve the otpauth URL to the user in a QR code. To do that, we can use the qrcode library.
twoFactorAuthentication.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 |
import { Injectable } from '@nestjs/common'; import { toFileStream } from 'qrcode'; import { Response } from 'express'; @Injectable() export class TwoFactorAuthenticationService { // ... public async pipeQrCodeStream(stream: Response, otpauthUrl: string) { return toFileStream(stream, otpauthUrl); } } |
Once we have all of the above, we can create a controller that uses this logic.
twoFactorAuthentication.controller.ts
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 |
import { ClassSerializerInterceptor, Controller, Header, Post, UseInterceptors, Res, UseGuards, Req, } from '@nestjs/common'; import { TwoFactorAuthenticationService } from './twoFactorAuthentication.service'; import { Response } from 'express'; import JwtAuthenticationGuard from '../jwt-authentication.guard'; import RequestWithUser from '../requestWithUser.interface'; @Controller('2fa') @UseInterceptors(ClassSerializerInterceptor) export class TwoFactorAuthenticationController { constructor( private readonly twoFactorAuthenticationService: TwoFactorAuthenticationService, ) {} @Post('generate') @UseGuards(JwtAuthenticationGuard) async register(@Res() response: Response, @Req() request: RequestWithUser) { const { otpauthUrl } = await this.twoFactorAuthenticationService.generateTwoFactorAuthenticationSecret(request.user); return this.twoFactorAuthenticationService.pipeQrCodeStream(response, otpauthUrl); } } |
Above, we use the RequestWithUser interface and require the user to be authenticated. If you want to know more about it, check out API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies
Calling the above endpoint results in the API returning a QR code. Our users can now scan it with the Google Authenticator application.
Turning on the two-factor authentication
So far, our users can generate a QR code and scan it with the Google Authenticator application. Now we need to implement the logic of turning on the two-factor authentication. It requires the user to provide the code from the Authenticator application. We then need to validate it against the secret string we’ve saved in the database while generating a QR code.
We need to save the information about the two-factor authentication being turned on in the database. To do that, let’s expand the entity of the user.
user.entity.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'; @Entity() class User { @PrimaryGeneratedColumn() public id: number; @Column({ default: false }) public isTwoFactorAuthenticationEnabled: boolean; // ... } export default User; |
We also need to create a method in the service to set this flag to true.
users.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import User from './user.entity'; @Injectable() export class UsersService { constructor( @InjectRepository(User) private usersRepository: Repository<User>, ) {} async turnOnTwoFactorAuthentication(userId: number) { return this.usersRepository.update(userId, { isTwoFactorAuthenticationEnabled: true }); } // ... } |
The most crucial part here is verifying the user’s code against the secret saved in the database. Let’s do that in the TwoFactorAuthenticationService:
twoFactorAuthentication.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import { Injectable } from '@nestjs/common'; import { authenticator } from 'otplib'; import User from '../../users/user.entity'; @Injectable() export class TwoFactorAuthenticationService { public isTwoFactorAuthenticationCodeValid(twoFactorAuthenticationCode: string, user: User) { return authenticator.verify({ token: twoFactorAuthenticationCode, secret: user.twoFactorAuthenticationSecret }) } // ... } |
Once we’ve got all of the above ready to go, we can use this logic in our controller:
twoFactorAuthentication.controller.ts
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 |
import { ClassSerializerInterceptor, Controller, Post, UseInterceptors, UseGuards, Req, Body, UnauthorizedException, HttpCode, } from '@nestjs/common'; import { TwoFactorAuthenticationService } from './twoFactorAuthentication.service'; import JwtAuthenticationGuard from '../jwt-authentication.guard'; import RequestWithUser from '../requestWithUser.interface'; import { TurnOnTwoFactorAuthenticationDto } from './dto/turnOnTwoFactorAuthentication.dto'; import { UsersService } from '../../users/users.service'; @Controller('2fa') @UseInterceptors(ClassSerializerInterceptor) export class TwoFactorAuthenticationController { constructor( private readonly twoFactorAuthenticationService: TwoFactorAuthenticationService, private readonly usersService: UsersService ) {} @Post('turn-on') @HttpCode(200) @UseGuards(JwtAuthenticationGuard) async turnOnTwoFactorAuthentication( @Req() request: RequestWithUser, @Body() { twoFactorAuthenticationCode } : TwoFactorAuthenticationCodeDto ) { const isCodeValid = this.twoFactorAuthenticationService.isTwoFactorAuthenticationCodeValid( twoFactorAuthenticationCode, request.user ); if (!isCodeValid) { throw new UnauthorizedException('Wrong authentication code'); } await this.usersService.turnOnTwoFactorAuthentication(request.user.id); } // ... } |
Above, we create a Data Transfer Object with the twoFactorAuthenticationCode property. If you want to know more about how to create DTOs with validation, check out API with NestJS #4. Error handling and data validation
Now, the user can generate a QR code, save it in the Google Authenticator application, and send a valid code to the /2fa/turn-on endpoint. If that’s the case, we acknowledge that the two-factor authentication has been saved.
Logging in with two-factor authentication
The next step in our two-factor authentication flow is allowing the user to log in. In this article, we implement the following approach:
- the user logs in using the email and the password, and we respond with a JWT token,
- if the 2FA is turned off, we give full access to the user,
- if the 2FA is turned on, we provide the access just to the /2fa/authenticate endpoint,
- the user looks up the Authenticator application code and sends it to the /2fa/authenticate endpoint; we respond with a new JWT token with full access.
The first missing part of the above flow is the route that allows the user to send the two-factor authentication code.
twoFactorAuthentication.controller.ts
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 |
import { ClassSerializerInterceptor, Controller, Post, UseInterceptors, UseGuards, Req, Body, UnauthorizedException, HttpCode, } from '@nestjs/common'; import { TwoFactorAuthenticationService } from './twoFactorAuthentication.service'; import JwtAuthenticationGuard from '../jwt-authentication.guard'; import RequestWithUser from '../requestWithUser.interface'; import { UsersService } from '../../users/users.service'; import { TwoFactorAuthenticationCodeDto } from './dto/twoFactorAuthenticationCode.dto'; import { AuthenticationService } from '../authentication.service'; @Controller('2fa') @UseInterceptors(ClassSerializerInterceptor) export class TwoFactorAuthenticationController { constructor( private readonly twoFactorAuthenticationService: TwoFactorAuthenticationService, private readonly usersService: UsersService, private readonly authenticationService: AuthenticationService ) {} @Post('authenticate') @HttpCode(200) @UseGuards(JwtAuthenticationGuard) async authenticate( @Req() request: RequestWithUser, @Body() { twoFactorAuthenticationCode } : TwoFactorAuthenticationCodeDto ) { const isCodeValid = this.twoFactorAuthenticationService.isTwoFactorAuthenticationCodeValid( twoFactorAuthenticationCode, request.user ); if (!isCodeValid) { throw new UnauthorizedException('Wrong authentication code'); } const accessTokenCookie = this.authenticationService.getCookieWithJwtAccessToken(request.user.id, true); request.res.setHeader('Set-Cookie', [accessTokenCookie]); return request.user; } // ... } |
A crucial thing to notice above is that we’ve added an argument to the getCookieWithJwtAccessToken method.
authentication.service.ts
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 |
import { Injectable } from '@nestjs/common'; import { UsersService } from '../users/users.service'; import { JwtService } from '@nestjs/jwt'; import { ConfigService } from '@nestjs/config'; import TokenPayload from './tokenPayload.interface'; @Injectable() export class AuthenticationService { constructor( private readonly usersService: UsersService, private readonly jwtService: JwtService, private readonly configService: ConfigService ) {} public getCookieWithJwtAccessToken(userId: number, isSecondFactorAuthenticated = false) { const payload: TokenPayload = { userId, isSecondFactorAuthenticated }; const token = this.jwtService.sign(payload, { secret: this.configService.get('JWT_ACCESS_TOKEN_SECRET'), expiresIn: `${this.configService.get('JWT_ACCESS_TOKEN_EXPIRATION_TIME')}s` }); return `Authentication=${token}; HttpOnly; Path=/; Max-Age=${this.configService.get('JWT_ACCESS_TOKEN_EXPIRATION_TIME')}`; } // ... } |
Thanks to setting the isSecondFactorAuthenticated property, we can now distinguish between tokens created with and without two-factor authentication.
Checking if the user is authenticated with the second factor
Since we can authenticate users using the second factor, we now should check it before we grant them access to various resources. In the third part of this series, we’ve created a Passport strategy that parses the cookie and the JWT token. Let’s expand on this idea and create a strategy and a guard that check if the two-factor authentication was successful.
authentication.service.ts
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 |
import { ExtractJwt, Strategy } from 'passport-jwt'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Request } from 'express'; import { UsersService } from '../users/users.service'; import TokenPayload from './tokenPayload.interface'; @Injectable() export class JwtTwoFactorStrategy extends PassportStrategy( Strategy, 'jwt-two-factor' ) { constructor( private readonly configService: ConfigService, private readonly userService: UsersService, ) { super({ jwtFromRequest: ExtractJwt.fromExtractors([(request: Request) => { return request?.cookies?.Authentication; }]), secretOrKey: configService.get('JWT_ACCESS_TOKEN_SECRET') }); } async validate(payload: TokenPayload) { const user = await this.userService.getById(payload.userId); if (!user.isTwoFactorAuthenticationEnabled) { return user; } if (payload.isSecondFactorAuthenticated) { return user; } } } |
Above, the crucial logic happens in the validate method. If the two-factor authentication is not enabled for the current user, we don’t check if the token contains the isSecondFactorAuthenticated flag.
To use the above strategy, we need to create a guard:
jwt-two-factor.guard.ts
1 2 3 4 5 |
import { Injectable } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Injectable() export default class JwtTwoFactorGuard extends AuthGuard('jwt-two-factor') {} |
We can now use it on endpoints that we want to protect with two-factor authentication.
posts.controller.ts
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 |
import { Body, Controller, Post, UseGuards, Req, UseInterceptors, ClassSerializerInterceptor, } from '@nestjs/common'; import PostsService from './posts.service'; import CreatePostDto from './dto/createPost.dto'; import RequestWithUser from '../authentication/requestWithUser.interface'; import JwtTwoFactorGuard from '../authentication/jwt-two-factor.guard'; @Controller('posts') @UseInterceptors(ClassSerializerInterceptor) export default class PostsController { constructor( private readonly postsService: PostsService ) {} @Post() @UseGuards(JwtTwoFactorGuard) async createPost(@Body() post: CreatePostDto, @Req() req: RequestWithUser) { return this.postsService.createPost(post, req.user); } // ... } |
It is crucial not to use the JwtTwoFactorGuard on the /2fa/authenticate endpoint, because we need users to access it before authenticating with the second factor.
Modifying the basic logging-in logic
The last step is modifying the regular /authentication/log-in endpoint. It always responds with the user’s data, even if we didn’t perform two-factor authentication yet. Let’s change it.
authentication.controller.ts
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 |
import { Req, Controller, HttpCode, Post, UseGuards, ClassSerializerInterceptor, UseInterceptors, } from '@nestjs/common'; import { AuthenticationService } from './authentication.service'; import RequestWithUser from './requestWithUser.interface'; import { LocalAuthenticationGuard } from './localAuthentication.guard'; import { UsersService } from '../users/users.service'; @Controller('authentication') @UseInterceptors(ClassSerializerInterceptor) export class AuthenticationController { constructor( private readonly authenticationService: AuthenticationService, private readonly usersService: UsersService ) {} @HttpCode(200) @UseGuards(LocalAuthenticationGuard) @Post('log-in') async logIn(@Req() request: RequestWithUser) { const { user } = request; const accessTokenCookie = this.authenticationService.getCookieWithJwtAccessToken(user.id); const { cookie: refreshTokenCookie, token: refreshToken } = this.authenticationService.getCookieWithJwtRefreshToken(user.id); await this.usersService.setCurrentRefreshToken(refreshToken, user.id); request.res.setHeader('Set-Cookie', [accessTokenCookie, refreshTokenCookie]); if (user.isTwoFactorAuthenticationEnabled) { return; } return user; } // ... } |
Summary
In this article, we’ve implemented a fully working two-factor authentication flow. Our users can now generate a unique, secret key, and we present them with a QR image. After turning on the two-factor authentication, we validate upcoming requests.
The above approach might benefit from additional features. An example would be support for backup codes that the user could use in case of losing the phone. I encourage you to improve the flow presented in this article.
Thank you again for this awesome work ,i’m really learning a lot from these articles , but i have a question in mind , can we create a Api gateway that dynamically proxy all the Api’s of one microservice or multiple microservices, maybe a service discovery , if not do you you know any tools or books that can help achieve that with Nest js ???
You should read about Templating in OOP, as nestjs use OOP structure, classes and their concepts, Templates can help you make dynamic functions and will give you more than enough power.
In my swagger/Postman I can’t generate the QR code like you did. It’s sending me back some extracted png format. How can I show this in swagger/Postman ? Even I don’t know it is working or not. I know it’s unrecognized but is there any way to show the QRcode ?
I found a solution and it works for me which is – add a line stream.setHeader(‘content-type’,’image/png’); in pipeQrCodeStream()
I think you should put that line on the controller level not the service level. For example on the @Post(‘generate’) add the below line before calling this.twoFactorAuthenticationService.pipeQrCodeStream,
response.setHeader(‘content-type’, ‘image/png’);
Thank you, great explanation.
Just a question how do I display the QR code on the website frontend.
Axios doesn’t seem to support fileStream in the browser and I’m not sure with Fetch how to go from a fileStream to a base64
Set the responseType to blob. Then const url = URL.createObjectURL (response);
Angular code example:
async generateQr(): Promise<void> {
try {
const response = await this.http.post(this.baseUrl + '/auth/generate', {}, {
headers: {
Authorization: 'Bearer' + ${this.token}
},
responseType: 'blob',
}).toPromise();
this.fileUrl = this.domSanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(response));
}catch (e) {
console.log(e);
}
}