27 lines
728 B
TypeScript
27 lines
728 B
TypeScript
import { ExtractJwt, Strategy, StrategyOptions } from 'passport-jwt';
|
|
import { PassportStrategy } from '@nestjs/passport';
|
|
import { Injectable } from '@nestjs/common';
|
|
|
|
interface JwtPayload {
|
|
sub: string;
|
|
username: string;
|
|
}
|
|
|
|
@Injectable()
|
|
export class JwtStrategy extends PassportStrategy(Strategy) {
|
|
constructor() {
|
|
const jwtExtractor = ExtractJwt.fromAuthHeaderAsBearerToken();
|
|
const options: StrategyOptions = {
|
|
jwtFromRequest: jwtExtractor,
|
|
ignoreExpiration: false,
|
|
secretOrKey: process.env.JWT_SECRET || 'your-secret-key',
|
|
};
|
|
|
|
super(options);
|
|
}
|
|
|
|
validate(payload: JwtPayload): { id: string; username: string } {
|
|
return { id: payload.sub, username: payload.username };
|
|
}
|
|
}
|