繁体   English   中英

使用 JWT 登录 Angular 10

[英]Login In Angular 10 with JWT

我在使用 angular 中的 JWT 登录时遇到问题,我已经通过登录成功登录并存储了令牌,但是我的前端没有使用相同的方式更新自身

身份验证服务.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ErrorprocessorService } from './errorprocessor.service';
import { Observable, Subject } from 'rxjs';
import { map } from 'rxjs/operators';

interface LogUser {
  success: boolean;
  message: string;
  token: string;
  user: {
    name: string;
    username: string;
    email: string;
  };
}

interface JWTResponse {
  success: boolean;
  message: string;
  user: any;
}

@Injectable({
  providedIn: 'root'
})

export class AuthService {

  tokenKey = 'JWT';
  isAuthenticated: Boolean = false;
  username: Subject<string> = new Subject<string>();
  authToken: string = undefined;

  constructor(private http: HttpClient, private errorProcessor: ErrorprocessorService) { }

  loadUserCredentials() {
    const credentials = JSON.parse(localStorage.getItem(this.tokenKey));
    console.log('Loading User Credentials : ', credentials);
    if (credentials && credentials.username !== undefined) {
      this.useCredentials(credentials);
      if (this.authToken) {
        this.checkJWTtoken();
      }
    }
  }

  checkJWTtoken() {
    this.http.get<JWTResponse>('http://localhost:3000/auth/checkToken')
      .subscribe(res => {
        console.log('JWT Token Valid: ', res);
        this.sendUsername(res.user.username);
      }, err => {
        console.log('JWT Token Invalid: ', err);
        this.destroyUserCedentials();
      });
  }

  storeUserCredentials(credentials: any) {
    console.log('Storing User Credentials : ', credentials);
    localStorage.setItem(this.tokenKey, JSON.stringify(credentials));
    this.storeUserCredentials(credentials);
  }

  useCredentials(credentials: any) {
    this.isAuthenticated = true;
    this.sendUsername(credentials.username);
    this.authToken = credentials.token;
  }

  sendUsername(name: string) {
    this.username.next(name);
  }

  loginUser(user: any): Observable<any> {

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    };

    return this.http.post<LogUser>('http://localhost:3000/auth/login', user, httpOptions)
      .pipe(map(res => {
        this.storeUserCredentials({ username: user.username, token: res.token });
        return { 'success': true, 'username': user.username };
      }))
  }

  destroyUserCedentials() {
    this.authToken = undefined;
    this.clearUsername();
    this.isAuthenticated = false;
    localStorage.removeItem(this.tokenKey);
  }

  clearUsername() {
    this.username.next(undefined);
  }

  logOut() {
    this.destroyUserCedentials();
  }

  isLoggedIn(): Boolean {
    return this.isAuthenticated;
  }

  getUsername(): Observable<string> {
    return this.username.asObservable();
  }

  getToken(): string {
    return this.authToken;
  }
}

登录组件.ts

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

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit {

  errMsg: string;
  user = {
    username: '',
    password: ''
  };

  constructor(private authService: AuthService, private router: Router) { }

  ngOnInit(): void {
  }

  onSubmit(): void {
    console.log(this.user);
    this.authService.loginUser(this.user)
      .subscribe(res => {
        if (res.success) {
          this.router.navigate(['/dashboard']);
        } else {
          console.log(res);
        }
      }, err => {
        this.errMsg = <any>err;
      });
  }

}

Auth-guard.server.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {

  constructor(public auth: AuthService, public router: Router) { }

  canActivate(): boolean {
    if (!this.auth.isLoggedIn()) {
      this.router.navigate(['login']);
      return false;
    }
    return true;
  }
}

Header.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  username: string = undefined;
  subscription: Subscription;

  constructor(private authService: AuthService, private router: Router) { }

  ngOnInit(): void {
    this.authService.loadUserCredentials();
    this.subscription = this.authService.getUsername()
      .subscribe(name => { console.log(name); this.username = name; });
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

  openProfile(): void {
    this.router.navigate(['/profile']);
  }

  logOut(): void {
    this.username = undefined;
    this.authService.logOut();
  }

}

谁能帮我这个? 在此先感谢,如果您需要任何其他文件,请联系我,我会发给您

您的代码有无限循环:

storeUserCredentials(credentials: any) {
    console.log('Storing User Credentials : ', credentials);
    localStorage.setItem(this.tokenKey, JSON.stringify(credentials));
    this.storeUserCredentials(credentials);
}

阻止您的应用程序运行可能是一个错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM