угловой веб-токен json x-auth-токен не сохранен должным образом с помощью интрецептора - PullRequest
2 голосов
/ 18 июня 2019

при входе в приложение angular я могу войти, но jwt неправильно сохраняется как x-auth-token с использованием углового перехватчика, который присоединяет токен в качестве заголовков для каждого запроса на вывод из приложения:

https://imgur.com/CqjA7Da

я могу консоль записать токен в журнал, так что я непременно получу его из бэкэнда, и он будет правильно создан в бэкэнде

попробовал некоторые методы для сохранения в токене как x-auth-токен, но не удалось

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 голосов
/ 18 июня 2019
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(['/']);
        }
      })
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...