Working with PassportJS
Detailed documentation on working with PassportJS library
Passport is the most popular node.js authentication library, well-known by the community and successfully used in many production applications. It's straightforward to integrate this library with a Nest application using the @nestjs/passport
module
Steps to Use Passport in NestJS
Install Dependencies You'll need to install
@nestjs/passport
,passport
, and any specific Passport strategies you want to use (e.g.,passport-jwt
,passport-facebook
, etc.).Create the Strategy A Passport strategy in NestJS is typically implemented as an injectable service by extending the
PassportStrategy
class from@nestjs/passport
. You use this class to implement the required strategy.Example: Facebook Strategy for OAuth Authentication
Here,
validate
is called when the strategy is triggered, and you check the credentials.Register the Strategy In your Auth Module, you register the strategy as a provider so that it can be injected and used.
Use the Strategy in a Guard, you apply Passport strategies using guards. NestJS has a built-in
AuthGuard
that integrates with Passport.Example: Facebook Auth Guard
The string
'
jwt'
refers to the strategy defined in the FacebookStrategy
class.Use the Guard in a Controller Now, you can apply the guard to a route in your controller to protect it using the Passport strategy.
Example: Using the JwtAuthGuard in a Controller
In this case JwtAuthenticationGuard will returns us Authenticated user data.
Key Components:
Strategy: Implements a specific authentication mechanism.
Guard: Applies the strategy to route handlers to protect them.
By using Passport strategies in NestJS, you can easily implement complex authentication mechanisms (like JWT, OAuth, etc.) in a modular and structured way.
Google oAuth2Facebook oAuth2
Last updated