如何处理服务器内部错误?Nestjs



如何处理错误,以便在用户未提供令牌时抛出UnauthorizedException。

现在我得到这个错误:

{
"statusCode": 500,
"message": "Internal server error"
}

ts:

canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
try {
const jwt = request.headers.authorization.split(' ')[1];
if (!jwt) {
throw new UnauthorizedException('Token is not provided.');
}
return this.jwtService.verify(jwt);
} catch (e) {
return false;
}
}

您可以尝试从文档中重新创建验证模块。或者尝试在每行上执行console.log()。

默认情况下,JWT内部模块工作良好。它可以自动编码和解码所有你需要的。

https://docs.nestjs.com/security/authentication

我使用中间件来实现这个目的。我将分享它的基本版本。

auth-middleware.ts

import {HttpStatus,Injectable,Logger,LoggerService,NestMiddleware,} from '@nestjs/common';
import { NextFunction } from 'express';
import { Request, Response } from 'express';
@Injectable()
export class AuthMiddleware implements NestMiddleware {
constructor(
private readonly authenticationService: AuthService, 
// (I use Firebase auth. You can inject JWT service here instead)
private readonly logger: LoggerService, // Good'ol logger
) {}
public async use(req: Request, res: Response, next: NextFunction) {
// Checks if req has authorization header
const header = req.headers['authorization'];
if (!header) {
// If no headers are present, returns a 401.
// I use problem+json
// Thats why you are seeing more fields in the response instead of just a 
// code and message
return res
.status(HttpStatus.UNAUTHORIZED)
.json({
title: 'Unauthorized',
detail: 'Invalid Token',
type: 'https://app-site.com/login',
status: HttpStatus.UNAUTHORIZED,
instance: 'login/null',
})
.setHeader('Content-Type', 'application/problem+json');
}
// Splitting "Bearer token" to ["Bearer","token"]
const token = header.split(' ')[1];
// Validating token with auth service
// It returns a "tuple" for me...you can have it return whatever you want
const [
authClaims, // Custom claims that is extracted from the JWT
result, // JWT Validation result (boolean)
authProviderUid, // Firebase UID
] = await this.authenticationService.verifyToken(token);
if (
!result || // If JWT is invalid
authClaims.accountStatus === AccountStatusList.Banned ||
authClaims.accountStatus === AccountStatusList.Suspended
) {
// You shall not pass
return res
.status(HttpStatus.UNAUTHORIZED)
.json({
title: 'Unauthorized',
detail: 'Invalid Token',
type: 'https://app-site.com/login',
status: HttpStatus.UNAUTHORIZED,
instance: 'login/null',
})
.setHeader('Content-Type', 'application/problem+json');
}
// Attaches the claims, result and UID with req for the next middleware(s)/controller
req['authResult'] = { authClaims, result, authProviderUid };
//Reassuring 
this.logger.log('Token verified', AuthMiddleware.name);
// next function from express
next();
}
}

接下来,在声明控制器的模块中,

api.module.ts

import { MiddlewareConsumer, Module, NestModule, RequestMethod, } from '@nestjs/common';
@Module({
imports: [
//...
],
controllers: [
AuthController,
ProfileController,
SubscriptionController
],
providers: [
//...
],
})
export class ApiModule implements NestModule {
public async configure(consumer: MiddlewareConsumer) {
consumer
.apply(AuthMiddleware)
// Exclude some paths
.exclude({ path: '/api/v1/auth/sign-up', method: RequestMethod.POST })
.forRoutes( // Your controller classes you want to run the middleware on
ProfileController,
SubscriptionController,
AuthController
);
}
}

工作原理

每个请求都经过指定的中间件(如果不排除路径)。如果请求未经授权,则在到达控制器之前抛出错误。

如果请求位于控制器,则请求经过身份验证。你必须照顾授权部分与警卫等…

Authentication和Authorization不一样

我建议使用中间件进行身份验证,使用警卫进行授权。

链接:

  1. NestJS中间件文档
  2. 问题详细信息

相关内容

  • 没有找到相关文章

最新更新