【问题标题】:'Authorization: Bearer Undefined''授权:承载未定义'
【发布时间】:2021-06-18 15:37:31
【问题描述】:

当我尝试登录时,授权标头始终未定义。尝试在我的 angular.json 文件中设置 AOT = false 但无济于事。这里有什么问题?

身份验证拦截器

import { HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { AuthService } from "./auth.service";


@Injectable()
export class AuthInterceptor implements HttpInterceptor{
    constructor(private authService: AuthService){}

    intercept(req: HttpRequest<any>, next: HttpHandler){
        const authToken = this.authService.getToken();
        const authRequest = req.clone({
            headers: req.headers.set("Authorization", "Bearer " + authToken)
        })
        return next.handle(authRequest)
    }   
}

后端的 checkAuth 中间件

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
    try{
        const token = req.headers.authorization.split(" ")[1]
        jwt.verify(token, "asderfghtyu")
        next();
    }
    catch(error) {
        res.status(401).json({
            message: "Authorization failed macha"
        })
    }
}

auth-service.ts

 export class AuthService {
  private token: string;

  constructor(private http: HttpClient) { }

  getToken(){
    return this.token;
  }
  
  createUser(FullName: string, email: string, role: string, password: string) {
    const authData: AuthData = { FullName: FullName, email: email, role: role, password: password }
    this.http.post("http://localhost:3300/api/user/signup", authData)
      .subscribe(result => {
        console.log(result);
      })
  }

  login(email: string, password: string){
    this.http.post<{token: string}>("http://localhost:3300/api/user/login", {email: email, password: password})
    .subscribe(response=>{
      const token = response.token;
      this.token = token;
    })
  }

 

这是存在getToken() 函数的auth-service.ts 文件

【问题讨论】:

  • 您设置标题的方式没有任何问题。从 this.authService.getToken(); 返回的内容是未定义的。
  • 我也用 auth-service 代码编辑了我的帖子。请看一看。

标签: node.js angular jwt authorization angular-http-interceptors


【解决方案1】:

在您的 Auth-Interceptor 中,替换 -

const authRequest = req.clone({
        headers: req.headers.set("Authorization", "Bearer " + authToken)
    })

与 -

const authRequest = !authToken ? req : req.clone({
        setHeaders: { Authorization: `Bearer ${authToken}` }
    });

仅当您有令牌时,这才会添加 Authorization 标头。如果authService.getToken() 返回undefined,则不会在请求中添加Authorization 标头。

【讨论】:

  • 还是一样。没有变化。 :(
  • @RP 然后将console.log(authToken); 放在该行之后 - const authToken = this.authService.getToken(); 并检查authToken 是否具有价值。
  • 一开始打印未定义,但在我第二次按下登录按钮后,它会打印令牌值
  • @RP 这是正常/预期的行为。当您第一次尝试登录时,请求标头将没有令牌,因为您尚未登录并且服务器尚未发出令牌。登录成功后,服务器会向您发出一个令牌,之后的任何请求的标头中都应该有一个令牌。
  • @RP 这就是(我在之前的评论中提到的)你的情况是怎么回事?如果是这样,那么我将删除此答案,并投票关闭该帖子。或者,您可能应该删除该帖子。
猜你喜欢
  • 1970-01-01
  • 2019-09-02
  • 2016-02-23
  • 2023-04-07
  • 2014-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多