NestJS: AuthGuard Cannot Use Inject in Its canActivate Function
Cause
Recently I was writing a nestjs project. Its UserGuard is very convenient — it is like, when a route handles a request, the verification code can be handled by AuthGuard.
But while writing it, I ran into a problem that took me a very long time to solve, for example the following StaffAuthGuard.ts code:
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
45
46
47
48
49
50
51
52
53
|
import { ExecutionContext, Inject, Injectable } from '@nestjs/common';
import { StaffAuthService } from './staff-auth.service';
import { of } from 'rxjs';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class StaffJwtAuthGuard extends AuthGuard('jwt') {
constructor(private authService: StaffAuthService) {
super(authService);
this.authService = authService;
console.log(
'🚀 ~ file: staff-auth.guard.ts:11 ~ StaffJwtAuthGuard ~ constructor ~ authService',
authService,
', this.authService: ',
this.authService,
);
}
canActivate(context: ExecutionContext) {
if (context.getType() != 'http') {
return false;
}
const authHeader = context.switchToHttp().getRequest()
.headers.authorization;
if (!authHeader) {
return false;
}
const authHeaderParts = authHeader.split(' ');
if (authHeaderParts.length != 2) {
return false;
}
const [, jwt] = authHeaderParts;
this.authService
.verifyJwt(jwt)
.then((res) => {
const exp = res.exp;
if (!exp) return of(false);
const TOKEN_EXP_MS = exp * 1000;
const isJwtValid = Date.now() < TOKEN_EXP_MS;
// return of(isJwtValid);
return isJwtValid;
})
.catch((err) => {
console.log(
'🚀 ~ file: staff-auth.guard.ts:35 ~ StaffJwtAuthGuard ~ canActivate ~ err',
err,
);
// return of(false);
return false;
});
return super.canActivate(context);
}
}
|
When calling the api, when it went through StaffAuthGuard.canActivate, it reported undefined. After adding logs, I found it was this line: