Skip to content

Instantly share code, notes, and snippets.

@thisismydesign
Last active September 6, 2023 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thisismydesign/5fd79017b1d55b74a5685bad4a849efa to your computer and use it in GitHub Desktop.
Save thisismydesign/5fd79017b1d55b74a5685bad4a849efa to your computer and use it in GitHub Desktop.
OAuth2 in NestJS for social login (Google, Facebook, Twitter, etc) /2
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { JwtAuthService } from './jwt-auth.service';
import { JwtAuthStrategy } from './jwt-auth.strategy';
@Module({
imports: [
JwtModule.registerAsync({
useFactory: async (configService: ConfigService) => {
return {
secret: configService.get<string>('JWT_SECRET'),
signOptions: {
expiresIn: configService.get<string>('JWT_EXPIRES_IN'),
},
};
},
inject: [ConfigService],
}),
],
providers: [JwtAuthStrategy, JwtAuthService],
exports: [JwtModule, JwtAuthService],
})
export class JwtAuthModule {}
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from './jwt-auth.strategy';
@Injectable()
export class JwtAuthService {
constructor(private jwtService: JwtService) {}
login(user) {
const payload: JwtPayload = { username: user.username, sub: user.id };
return {
accessToken: this.jwtService.sign(payload),
};
}
}
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
export type JwtPayload = { sub: number; username: string };
@Injectable()
export class JwtAuthStrategy extends PassportStrategy(Strategy) {
constructor(configService: ConfigService) {
const extractJwtFromCookie = (req) => {
let token = null;
if (req && req.cookies) {
token = req.cookies['jwt'];
}
return token;
};
super({
jwtFromRequest: extractJwtFromCookie,
ignoreExpiration: false,
secretOrKey: configService.get<string>('JWT_SECRET'),
});
}
async validate(payload: JwtPayload) {
return { id: payload.sub, username: payload.username };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment