使用Intreceptor无法正确保存angular json网络令牌x-auth-token

时间:2019-06-18 09:23:39

标签: angular jwt

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

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);
    }
  }

}

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

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(['/']);
        }
      })
  }