Browse Source

feat(auth): 添加检查Bearer Token的接口并优化验证逻辑

- 在AuthController中添加新的check接口用于验证Authorization头中的Bearer Token
- 优化AuthService中的验证逻辑,将token.substring(7)直接内联到比较语句中
- 新增接口返回401状态码用于未授权访问
Sakulin 2 months ago
parent
commit
c8ab259b52
2 changed files with 15 additions and 3 deletions
  1. 14 1
      src/auth/auth.controller.ts
  2. 1 2
      src/auth/auth.service.ts

+ 14 - 1
src/auth/auth.controller.ts

@@ -1,4 +1,4 @@
-import { Controller, Post, Body } from '@nestjs/common';
+import { Controller, Post, Body, Headers } from '@nestjs/common';
 import { AuthService } from './auth.service';
 
 interface AuthBody {
@@ -22,4 +22,17 @@ export class AuthController {
       msg: 'Wrong password',
     };
   }
+
+  @Post('check')
+  check(@Headers('Authorization') token: string) {
+    return this.authService.checkBearerToken(token)
+      ? {
+          code: 200,
+          msg: 'OK',
+        }
+      : {
+          code: 401,
+          msg: 'Unauthorized',
+        };
+  }
 }

+ 1 - 2
src/auth/auth.service.ts

@@ -26,7 +26,6 @@ export class AuthService {
     if (!token.startsWith('Bearer ')) {
       return false;
     }
-    token = token.substring(7);
-    return this.bearerToken === token;
+    return this.bearerToken === token.substring(7);
   }
 }