【问题标题】:angular json web token x-auth-token not saved properly using intreceptor角度 json web 令牌 x-auth-token 未使用 intreceptor 正确保存
【发布时间】:2019-10-31 21:42:11
【问题描述】:

当登录到 Angular 应用程序时,我可以登录,但 jwt 没有正确保存为 x-auth-token,使用 angular 拦截器将令牌作为来自应用程序的每个输出请求的标头附加:

https://imgur.com/CqjA7Da

我可以控制台记录令牌,所以我肯定会从后端获取它,并且它是在后端正确创建的

尝试了一些方法将令牌保存为 x-auth-token,但没有成功

auth-interceptor.ts:

import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AuthService } from '../services/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('x-auth-token', authToken)
    });
    return next.handle(authRequest);
  }
}

auth.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AuthData } from './../models/auth-data';
import { UserStatuses } from '../enums/user-statuses';
import { UserTypes } from '../enums/user-types';
import { LoginAuthData } from './../models/login-auth-data';
import { Subject } from 'rxjs';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private isAuthenticated: boolean = false
  private token: string = ' ';
  private authStatusListener = new Subject<boolean>();

  constructor(private _http: HttpClient,
    private _router: Router) { }

  getToken() {
    return this.token;
  }

  getIsAuth() {
    return this.isAuthenticated;
  }

  getAuthStatusListener() {
    return this.authStatusListener.asObservable();
  }

  createUser(firstName: string, lastName: string, email: string, position: string, password: string, companyName: string, country: string, city: string, state: string, zipCode: string, address: string, vat: string, userType: UserTypes, userStatus: UserStatuses) {
    const authData: AuthData = { firstName: firstName, lastName: lastName, email: email, position: position, password: password, companyName: companyName, country: country, city: city, state: state, zipCode: zipCode, address: address, vat: vat, userType: userType, userStatus: userStatus };
    this._http.post('http://localhost:5000/api/users/signup', authData)
      .subscribe(response => {
        console.log(response);
      })
    this._router.navigate(['/login']);
  }

  loginUser(email: string, password: string) {
    const loginAuthData: LoginAuthData = { email: email, password: password };
    this._http.post<{ token: string }>('http://localhost:5000/api/users/login', loginAuthData)
      .subscribe(response => {
        const token = response.token;
        this.token = token;
        if (token) {
          this.isAuthenticated = true;
          this.authStatusListener.next(true);
          this._router.navigate(['/']);
        }
      })
  }

  logout() {
    this.token = null;
    this.isAuthenticated = false;
    this.authStatusListener.next(false);
    window.location.reload();
  }
}

login.component.ts:

import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  email: string = '';
  password: string = '';

  constructor(private _authService: AuthService) { }

  ngOnInit() {
  }

  onSubmit({ value, valid }): void {
    if (valid) {
      console.log(value);
      this._authService.loginUser(value.email, value.password);
    }
  }

}

如何解决这个问题?

【问题讨论】:

    标签: angular jwt


    【解决方案1】:
    Its not an issue, You are getting the token from login api only, until it came from backend it supposed to be empty only.
    
    Look out the assignment of token property in
    auth.service.ts :
    
    export class AuthService {
      private isAuthenticated: boolean = false
      private token: string = ' ';
    
      constructor(private _http: HttpClient,
        private _router: Router) { }
    
      getToken() {
        return this.token;
      }
    
    
      loginUser(email: string, password: string) {
        const loginAuthData: LoginAuthData = { email: email, password: password };
        this._http.post<{ token: string }>('http://localhost:5000/api/users/login', loginAuthData)
          .subscribe(response => {
            const token = response.token;
            this.token = token;
            if (token) {
              this.isAuthenticated = true;
              this.authStatusListener.next(true);
              this._router.navigate(['/']);
            }
          })
      }
    

    【讨论】:

      猜你喜欢
      • 2016-03-14
      • 2015-10-27
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 2016-09-19
      • 2016-05-19
      相关资源
      最近更新 更多