2017-10-02 2 views
1

각도 4 프로젝트에서 JWT 인증을 구현하려고합니다. 서버 측은 모두 설정되어 있으며 프런트 엔드에만 추가 작업이 필요합니다.각도 2 UI 라우터 인증

이 라이브러리를 찾았습니다. auth0/angular2-jwt 하지만 내 관심사는 라이브러리가 ngRoute (확실하지 않음) 용으로 디자인 된 것처럼 보이지만 내 프로젝트에서 ui-router를 사용한다는 것입니다. 이 UI-Router/ngRoute 문제가 중요합니까? 내 프로젝트에서이 라이브러리를 사용할 수 있습니까?

또는 UI-Router와 함께 Angular 2/4 용으로 설계된 다른 인증 라이브러리가 있습니까?

답변

1

사용하는 모든 라우팅 환경 설정에서 작동합니다. 일관되게 사용하게 될 일반적인 항목은 'tokenNotExpired'뿐 아니라 물론 로컬 저장소에 토큰을 추가하고 디코딩하는 것입니다.

저는 이것을 프로덕션에서 6 개 프로젝트에 사용했으며, 원하는만큼 복잡하게 만들 수 있습니다 (또는 최소한으로, 일반적으로 어떻게 사용하는지). 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.isLoggedIn() 등의 작업에 액세스 할 수있는 다른 구성 요소에 AuthService을 가져 사용자가 authService.getUserName()으로 로그인 한 경우 boolean을 반환하여 사용자 이름을 문자열로 반환합니다.

+0

정말 고마워요. 각도 2-jwt 라이브러리를 사용할 것입니다. 당신이 그것을 구현하는 방법의 예제가 있다면 궁금해? – Viv

+0

@Viv 나는 auth.service와 user.service를 가지고있는 가장 기본적인 예제를 가지고있다. 내가이 항목들을 어떻게 처리하는지 추가하겠습니다. –

+0

@Viv updated 대답 –