Understanding Passport & OAuth Authentication
What is Authentication? Authentication is the act of figuring out who a user is. Example: You do username/password login to a website. Website figures out if you are really a user. What is Passport? Passport is a Node.js middleware. It helps deliver authentication (login mechanisms). It's extremely flexible and modular. Key Features of Passport: Minimalistic: Not going to force you to do things a certain way. Has support for over 500 strategies (username/password, Google, Facebook, etc.). Works perfectly with Express, NestJS, and most Node.js frameworks. Remember: Passport DOESN'T handle sessions, cookies, or databases itself. You write that code yourself if needed. What is a Strategy in Passport? A Strategy is a Passport plugin. It defines how you want to authenticate users. Examples of Strategies: passport-local: Login with username + password passport-jwt: Login with JWT tokens passport-google-oauth20: Login with Google account passport-facebook: Login with Facebook You can use more than one strategy in the same project! What is OAuth? OAuth (Open Authorization) is an open authorization standard protocol. It allows users to share access to their data without giving out passwords. Example: You click "Login with Google" => Google asks for permission => You authorize => Site gets your email/profile. How OAuth2 Works (Flow) User clicks "Login with Google". Client App (your app) redirects user to Google's login page. User logs in on Google and grants permission. Google sends an authorization code back to your app. Your app exchanges that code for an access token. Your app uses the access token to get user info (email, name, etc.). Your app logs in the user. This keeps the user's password secure. Only tokens are exchanged, not passwords. Passport + OAuth + NestJS Flow Install Passport Install OAuth Strategy (like passport-google-oauth20) Setup a strategy Setup routes for login and callback Extract user info after successful login Practical Example: Google OAuth with NestJS Step 1: Install Required Packages npm install @nestjs/passport passport passport-google-oauth20 npm install @nestjs/jwt passport-jwt npm install @types/passport-google-oauth20 --save-dev Step 2: Create the Google Strategy src/auth/google.strategy.ts import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy, VerifyCallback } from 'passport-google-oauth20'; @Injectable() export class GoogleStrategy extends PassportStrategy(Strategy, 'google') { constructor() { super({ clientID: 'YOUR_GOOGLE_CLIENT_ID', // ←replace with your credentials clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET', // ← replace with your credentials callbackURL: 'http://localhost:3000/auth/google/callback', scope: ['email', 'profile'], }); } async validate(accessToken: string, refreshToken: string, profile: any, done: VerifyCallback): Promise { const { name, emails, photos } = profile; const user = { email: emails[0].value, firstName: name.givenName, lastName: name.familyName, picture: photos[0].value, accessToken, }; done(null, user); } } Step 3: Create Auth Controller src/auth/auth.controller.ts import { Controller, Get, Req, UseGuards } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Controller('auth') export class AuthController { @Get('google') @UseGuards(AuthGuard('google')) async googleAuth(@Req() req) { // This route will redirect user to Google login } @Get('google/callback') @UseGuards(AuthGuard('google')) async googleAuthRedirect(@Req() req) { // This route is hit after login success return { message: 'User information from Google', user: req.user, }; } } Step 4: Create Auth Module src/auth/auth.module.ts import { Module } from '@nestjs/common'; import { AuthController } from './auth.controller'; import { GoogleStrategy } from './google.strategy'; @Module({ controllers: [AuthController], providers: [GoogleStrategy], }) export class AuthModule {} Step 5: Import AuthModule in App Module src/app.module.ts import { Module } from '@nestjs/common'; import { AuthModule } from './auth/auth.module'; @Module({ imports: [AuthModule], }) export class AppModule {} How It Works Now: Open browser => http://localhost:3000/auth/google You get redirected to Google Login page. After login => Google redirects to http://localhost:3000/auth/google/callback Your user information (email, name, photo) is read by the app. User can be saved in database, session can be created, or JWT can be created here. Concept Meaning Passport Middleware to make authentication easier OAuth Protocol to allow login via third parties like Google, Facebook Strategy Plugin (e.g.: GoogleStrategy) to handle specific log
What is Authentication?
Authentication is the act of figuring out who a user is.
Example:
- You do username/password login to a website.
- Website figures out if you are really a user.
What is Passport?
- Passport is a Node.js middleware.
- It helps deliver authentication (login mechanisms).
- It's extremely flexible and modular.
Key Features of Passport:
- Minimalistic: Not going to force you to do things a certain way.
- Has support for over 500 strategies (username/password, Google, Facebook, etc.).
- Works perfectly with Express, NestJS, and most Node.js frameworks.
Remember: Passport DOESN'T handle sessions, cookies, or databases itself. You write that code yourself if needed.
What is a Strategy in Passport?
- A Strategy is a Passport plugin.
- It defines how you want to authenticate users.
Examples of Strategies:
- passport-local: Login with username + password
- passport-jwt: Login with JWT tokens
- passport-google-oauth20: Login with Google account
- passport-facebook: Login with Facebook
- You can use more than one strategy in the same project!
What is OAuth?
- OAuth (Open Authorization) is an open authorization standard protocol.
- It allows users to share access to their data without giving out passwords.
Example:
You click "Login with Google" => Google asks for permission => You authorize => Site gets your email/profile.
How OAuth2 Works (Flow)
- User clicks "Login with Google".
- Client App (your app) redirects user to Google's login page.
- User logs in on Google and grants permission.
- Google sends an authorization code back to your app.
- Your app exchanges that code for an access token.
- Your app uses the access token to get user info (email, name, etc.).
- Your app logs in the user.
- This keeps the user's password secure.
- Only tokens are exchanged, not passwords.
Passport + OAuth + NestJS Flow
- Install Passport
- Install OAuth Strategy (like passport-google-oauth20)
- Setup a strategy
- Setup routes for login and callback
- Extract user info after successful login
Practical Example: Google OAuth with NestJS
Step 1: Install Required Packages
npm install @nestjs/passport passport passport-google-oauth20
npm install @nestjs/jwt passport-jwt
npm install @types/passport-google-oauth20 --save-dev
Step 2: Create the Google Strategy
src/auth/google.strategy.ts
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor() {
super({
clientID: 'YOUR_GOOGLE_CLIENT_ID', // ←replace with your credentials
clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET', // ← replace with your credentials
callbackURL: 'http://localhost:3000/auth/google/callback',
scope: ['email', 'profile'],
});
}
async validate(accessToken: string, refreshToken: string, profile: any, done: VerifyCallback): Promise {
const { name, emails, photos } = profile;
const user = {
email: emails[0].value,
firstName: name.givenName,
lastName: name.familyName,
picture: photos[0].value,
accessToken,
};
done(null, user);
}
}
Step 3: Create Auth Controller
src/auth/auth.controller.ts
import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Controller('auth')
export class AuthController {
@Get('google')
@UseGuards(AuthGuard('google'))
async googleAuth(@Req() req) {
// This route will redirect user to Google login
}
@Get('google/callback')
@UseGuards(AuthGuard('google'))
async googleAuthRedirect(@Req() req) {
// This route is hit after login success
return {
message: 'User information from Google',
user: req.user,
};
}
}
Step 4: Create Auth Module
src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { GoogleStrategy } from './google.strategy';
@Module({
controllers: [AuthController],
providers: [GoogleStrategy],
})
export class AuthModule {}
Step 5: Import AuthModule in App Module
src/app.module.ts
import { Module } from '@nestjs/common';
import { AuthModule } from './auth/auth.module';
@Module({
imports: [AuthModule],
})
export class AppModule {}
How It Works Now:
- Open browser => http://localhost:3000/auth/google
- You get redirected to Google Login page.
- After login => Google redirects to http://localhost:3000/auth/google/callback
- Your user information (email, name, photo) is read by the app.
- User can be saved in database, session can be created, or JWT can be created here.
Concept Meaning
- Passport Middleware to make authentication easier
- OAuth
- Protocol to allow login via third parties like Google, Facebook
- Strategy
- Plugin (e.g.: GoogleStrategy) to handle specific login method
- NestJS Integration
- You implement Guards and Strategies for redirection and login
Final Key Points
- Never make your Google client secret public.
- Use environment variables (.env file) for secret credentials.
- You can also extend the same for Facebook, Github, LinkedIn by just changing the strategy.
- Once OAuth login is done, generally you generate your own JWT token to manage user sessions.
If you want, after this you can:
- Automatically save user information to your database after login.
- Issue your own JWT tokens following an OAuth login.
- Protect specific routes so that only authenticated users can access them.