-
Notifications
You must be signed in to change notification settings - Fork 25
/
jwt.strategy.ts
44 lines (38 loc) · 1.35 KB
/
jwt.strategy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { Injectable, UnauthorizedException, Inject } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy as BaseStrategy, ExtractJwt } from 'passport-jwt';
import { passportJwtSecret } from 'jwks-rsa';
import { JwtPayload } from './interfaces/jwt-payload.interface';
@Injectable()
export class JwtStrategy extends PassportStrategy(BaseStrategy) {
constructor(configService: ConfigService) {
super({
secretOrKeyProvider: passportJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${configService.get<string>(
'auth.domain',
)}/.well-known/jwks.json`,
}),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
audience: configService.get<string>('auth.audience'),
issuer: `https://${configService.get<string>('auth.domain')}/`,
algorithms: ['RS256'],
});
}
validate(payload: JwtPayload): JwtPayload {
const minimumScope = ['openid', 'profile', 'email'];
if (
payload?.scope
?.split(' ')
.filter((scope) => minimumScope.indexOf(scope) > -1).length !== 3
) {
throw new UnauthorizedException(
'JWT does not possess the required scope (`openid profile email`).',
);
}
return payload;
}
}