Angular 2 UI-路由器认证

Angular 2 UI-Router Authentication

我正在尝试在我的 angular 4 项目中实施 JWT 身份验证。服务器端已经准备好了,只有前端需要一些额外的工作。

我找到了这个 auth0/angular2-jwt 图书馆。但我担心的是,我在项目中使用 ui-router,而库似乎是为 ngRoute 设计的(不确定)。 UI-Router/ngRoute 这件事重要吗?我可以只在我的项目中使用这个库吗?

或者是否有任何其他为 Angular 2/4 和 UI-Router 设计的身份验证库?

这适用于您使用的任何路由首选项。您会发现自己经常使用的一般项目是 'tokenNotExpired',当然还有将令牌添加到本地存储并对其进行解码。

我已经在六个生产项目中使用过它,它可以像你想要的那样复杂(或者最小化,这通常是我使用它的方式)。 angular2-jwt 是一个非常适合在 Angular 4+ 项目中处理 JWT 的库,一直得到很好的维护。

auth.service

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from './user.service';
import { tokenNotExpired, JwtHelper } from 'angular2-jwt';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/Rx';

@Injectable()
export class AuthService {
  jwtHelper: JwtHelper = new JwtHelper();
  _authChange: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
  authChange = this._authChange.asObservable();

  constructor(private userService: UserService,
              private router: Router) { }

  login(emailAndPassword) {
    return this.userService.login(emailAndPassword)
    .map(
      res => {
        localStorage.setItem('token', res.token);
        this._authChange.next(!this._authChange.getValue());
        return this.loggedIn;
      }
    );
  }

  logout() {
    localStorage.removeItem('token');
    this._authChange.next(!this._authChange.getValue());
    this.router.navigate(['/']);
  }

  getUserName() {
    if ( this.loggedIn() ) {
      return this.jwtHelper.decodeToken(localStorage.getItem('token')).user.username;
    } else {
      return '';
    }
  }

  getId() {
    if ( this.loggedIn() ) {
      return this.jwtHelper.decodeToken(localStorage.getItem('token')).user._id;
    } else {
      return '';
    }
  }

  loggedIn() {
    return tokenNotExpired();
  }

  isAuthChange(): Observable<boolean> {
    return this.authChange;
  }

}

user.service

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/timeout';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';


@Injectable()
export class UserService {

  // Headers
  headers = new HttpHeaders()
              .set('Content-Type', 'application/json')
              .set('charset', 'UTF-8' );

  constructor(private http: HttpClient) { }

  register(user): Observable<any> {
    console.log('Attempting to insert user doc into tempuser collection');
    console.log (user);
    return this.http.post('/api/tempuser', JSON.stringify(user), { headers: this.headers }).timeout(1500);
  }

  login(credentials): Observable<any> {
    return this.http.post('/api/login', JSON.stringify(credentials), { headers: this.headers });
  }

}

我在根 app.module 中提供这两种服务,并在其他组件中导入 AuthService 以访问诸如 authService.isLoggedIn() 到 return 之类的东西,如果用户是布尔值也登录 authService.getUserName() 到 return 用户名作为字符串。