私はSC93jsアプリケーションを作成し、リクエストオブジェクト内のトークンとトークンペイロード内のユーザーを検証する認証ガードをミドルウェアで検証したいと考えています。
これを分割することで、私はきれいな分離を望んでいました。まず私のミドルウェア
@Injectable()
export class TokenMiddleware implements NestMiddleware {
use(req: any, res: Response, next: NextFunction) {
try {
const headers: IncomingHttpHeaders = req.headers;
const authorization: string = headers.authorization;
const bearerToken: string[] = authorization.split(' ');
const token: string = bearerToken[1];
// !! Check if token was invalidated !!
req.token = token;
req.tokenPayload = verifyToken(token);
next();
} catch (error) {
throw new UnauthorizedException();
}
}
}
トークンのみを検証し、エンコードされたトークンとそのペイロードで要求オブジェクトを拡張します。私の認証ガード
@Injectable()
export class AuthenticationGuard implements CanActivate {
constructor(private readonly usersService: UsersService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request: any = context.switchToHttp().getRequest();
try {
const user: any = request.tokenPayload;
if (!user) {
throw new Error();
}
const findByIdDTO: FindByIdDTO = { id: user.id };
const existingUser: UserRO = await this.usersService.findById(findByIdDTO);
if (!existingUser) {
throw new Error();
}
// attach the user to the request object?
return true;
} catch (error) {
throw new UnauthorizedException();
}
}
}
このガードは、tokenpayload内の提供されたユーザーが有効なユーザーであるかどうかをチェックします。すべてが問題ない場合は、ユーザーをリクエストオブジェクトにどこにアタッチする必要がありますか?私が知る限り、ガードは何かが正しいかどうかをチェックするだけです。しかし、私はこのロジックをすべてトークンミドルウェアに保存したくありません。認証ガードで検証を終