Created
January 3, 2021 12:05
-
-
Save sebastiangug/74f4440406eab2534e1cdb64b895c221 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Help file for those experiencing the unmovable 401 for the passport-jwt auth implementation with nest. | |
// make sure to keep all configuration exactly like in the documentation -- this is in addition to that, not to replace that. | |
// unless directly specified | |
// STRATEGY | |
import { Injectable } from '@nestjs/common'; | |
import { Strategy, ExtractJwt } from 'passport-jwt'; | |
import { PassportStrategy } from '@nestjs/passport'; | |
@Injectable() | |
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') { | |
constructor() { | |
super({ | |
jwtFromRequest: ExtractJwt.fromHeader('access-token'), | |
ignoreExpiration: false, | |
secretOrKey: `${process.env.SECRET_KEY}`, | |
}); | |
} | |
async validate(payload: any) { | |
return payload; | |
} | |
} | |
// generate a new guard using the CLI => nest g guard CustomJWTGuard | |
// GUARD BELOW | |
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; | |
import { JwtService } from '@nestjs/jwt'; | |
import { Observable } from 'rxjs'; | |
@Injectable() | |
export class CustomJWTGuard implements CanActivate { | |
constructor(private jwtService: JwtService) {} | |
canActivate( | |
context: ExecutionContext, | |
): boolean | Promise<boolean> | Observable<boolean> { | |
const req: Request = context.switchToHttp().getRequest(); | |
const token = req.headers['access-token']; | |
const payload_data = this.jwtService.verify(token); | |
console.log('VERIFICATION', verification); | |
return true; | |
} | |
} | |
// in your route, protect it like so: | |
@UseGuards(AuthGuard('jwt')) | |
@Get('test') | |
async testReq() { | |
console.log('REQUEST SUCCESSFUL'); | |
return { successs: true }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment