拦截器中未定义令牌

发布于 2025-01-09 11:43:20 字数 1406 浏览 0 评论 0原文

我在使用 JWT 验证用户身份并允许访问我正在开发的网站的某些区域时遇到了问题。

确认用户存在于数据库中工作正常,我可以在后端创建令牌,没有任何问题,但是当我尝试在拦截器中使用令牌时,它不起作用。这是我的登录功能。

getToken() {
    // get token returns undefined
    return this.token;
}

    userLogin(email: string, password: string) {
    const authData: AuthData = { email: email, password: password };
    this.http.post<{ token: string }>('http://localhost:3000/api/auth/login', authData).subscribe((response) => {
        const token = response.token;
        this.token = token;
    });

令牌被声明为私有变量,这就是为什么我有在下面的拦截器中使用的 gettoken 函数。

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { UserAuthService } from './auth.service';

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

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('auth-interceptor.ts intercept() Token = ', this.authService.getToken());
        const authToken = this.authService.getToken();
        const authRequest = req.clone({
        headers: req.headers.set('Authorization', authToken)
        });
        return next.handle(authRequest);
    }
}

任何有关这方面的帮助将不胜感激,谢谢。

I have been having a problem with using JWT for authenticating users and allowing access to certain areas of a site I'm working on.

Confirming the user exists in the database works fine and I can create tokens on the backend with no problems but when I try to use the token in my interceptor it doesn't work. This is my login function.

getToken() {
    // get token returns undefined
    return this.token;
}

    userLogin(email: string, password: string) {
    const authData: AuthData = { email: email, password: password };
    this.http.post<{ token: string }>('http://localhost:3000/api/auth/login', authData).subscribe((response) => {
        const token = response.token;
        this.token = token;
    });

The token is declared as a private variable which is why I have the gettoken function which I use in the intercepter below.

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { UserAuthService } from './auth.service';

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

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('auth-interceptor.ts intercept() Token = ', this.authService.getToken());
        const authToken = this.authService.getToken();
        const authRequest = req.clone({
        headers: req.headers.set('Authorization', authToken)
        });
        return next.handle(authRequest);
    }
}

any help with this would be greatly appreciated, thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

世态炎凉 2025-01-16 11:43:20

您需要在模块中提供拦截器:

providers: [
    { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
]

You need to provide your interceptor in your module:

providers: [
    { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
]
给妤﹃绝世温柔 2025-01-16 11:43:20

正如评论中提到的,您应该确保您的服务中有 @Injectable({providedIn: 'root'}) ,否则该服务可能不是单例,并且您将拥有该类的多个实例。这可以解释令牌丢失的原因。

看看发生了什么也是一个技巧,可以像这样更改代码:

  private _token: string;
  get token(): string {
    console.log('getting token: ', this._token);
    return this._token;
  }
  set token(token: string) {
    console.log('setting token: ', token);
    this._token = token;
  }

然后您可以简单地执行 this.token = token;const authToken = this.authService.token;你应该看到日志。

还要按顺序在服务构造函数中添加一个 console.log() ,以便查看是否有同一服务的多个实例。

As mentioned in a comment, you should make sure to have @Injectable({providedIn: 'root'}) in your service otherwise the Service might not be a Singleton and you will have multiple instances of the class. This could explain why the token is missing.

also a trick to see what is happening, change the code like this:

  private _token: string;
  get token(): string {
    console.log('getting token: ', this._token);
    return this._token;
  }
  set token(token: string) {
    console.log('setting token: ', token);
    this._token = token;
  }

you can then simply do this.token = token; and const authToken = this.authService.token; and you should see the logs.

also add a console.log() in the service constructor in order so see if you have multiple instances of the same service.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文