【问题标题】:Angular 2 UI-Router AuthenticationAngular 2 UI-路由器身份验证
【发布时间】:2018-03-14 01:11:08
【问题描述】:

我正在尝试在我的 Angular 4 项目中实现 JWT 身份验证。服务器端已经设置好了,只是前端需要做一些额外的工作。

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

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

【问题讨论】:

    标签: angular angular-ui-router auth0 angular-router


    【解决方案1】:

    这适用于您使用的任何路由首选项。您会发现自己经常使用的一般项目是“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() 之类的内容,如果用户也登录则返回布尔值authService.getUserName() 以返回用户名作为一个字符串。

    【讨论】:

    • 非常感谢。我将使用 angular2-jwt 库。只是想知道您是否有一个如何实现它的示例?
    • @Viv 我非常喜欢他们拥有 auth.service 和 user.service 的最基本示例。我将继续在答案中添加我处理这些项目的方式。
    猜你喜欢
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 2021-12-16
    • 2018-12-19
    • 2021-12-20
    • 2016-12-11
    • 2017-02-24
    • 1970-01-01
    相关资源
    最近更新 更多