2017-04-18 6 views
0

成功したらJWTトークンを提供するexpress apiを呼び出して、Angular 2 appからユーザーを認証しようとしています。私は明確に疑う余地があります。角2のjwtトークンのクッキーを設定する方法

たちはクッキーを設定することが明示頼むか、あなたが角度でそれをしなければならないトークン

loginUser(email: string, password: string) { 
     let headers = new Headers({ 'Content-Type': 'application/json'}); 
     let options = new RequestOptions({headers: headers}); 
     let loginInfo = { email: email, password: password }; 

     return this.http.post('/auth/login', JSON.stringify(loginInfo), options) 
     .do(resp => { 
      // Do I need to set the cookie from here or it from the backend? 
     }).catch(error => { 
      return Observable.of(false); 
     }) 
    } 
+1

私はAngularが仕事をすると思います。ローカルストレージも使用できます。 –

答えて

1

でクッキーを設定するための角度仕事です行います。私は個人的にそれのためにlocalStorageを使用します。あなたが角度を使用して、それを実行する必要があり

login(email: string, password: string) { 
    const body = { email, password }; 
    return this._http.post('http://localhost:8000/api/auth/authenticate', body) 
     .map(response => { 
      const jsonRes = response.json(); 
      if(jsonRes.status == 'success') { 
       // Auth token 
       localStorage.setItem('auth_token', jsonRes.data.token); 
      } 
      return jsonRes; 
     }) 
     .catch(error => Observable.throw(error.json())); 
} 
2

:私の認証サービスから

例。はい、localstorageを使用することをお勧めしますが、使用することをお勧めします。Cookie

ここに私のangular2アプリケーションで使用したコードのサンプルがあります。あなたはなAuthCookieを検証するためにラインの下に使用することができます

login.ts

import { Component, OnInit, Input } from '@angular/core'; 
import { ActivatedRoute, Router } from '@angular/router'; 
import { AjaxLoader } from '../shared/services/ajax-loader'; 
import { UserService } from '../shared/services/user.service'; 
import { AuthCookie } from '../shared/services/auth-cookies-handler'; 

export class LoginComponent implements OnInit { 
    constructor(
    private router: Router, 
    private route: ActivatedRoute, 
    private userService: UserService, 
    private ajaxLoader: AjaxLoader, 
    private _authCookie: AuthCookie) { 
    this.ajaxLoader.startLoading(); 

    this.loginInfo = new User(); 
    this.registrationInfo = new User(); 
    } 

    validateUserAccount(event: Event) { 
    event.stopPropagation(); 
    event.preventDefault(); 

    this.userService.validateUserAccount(this.loginInfo) 
     .subscribe(
     (data: any) => { 
      if (data.user === "Invalid") { 
       this.isInvalidLogin = true; 
      } else { 
        this._authCookie.setAuth(JSON.stringify(data)); 
        this.router.navigate(['/home']); 

      } 
     }, 
     error => { 
      if (error.status === 404) { 
       this.isInvalidLogin = true; 
      } 
      this.ajaxLoader.completeLoading(); 
     }, 
     () => { 
      this.ajaxLoader.completeLoading(); 
     } 
     ); 
    } 
} 

のauth-クッキー-handler.ts

import { Injectable } from '@angular/core'; 
import { Cookie } from 'ng2-cookies/ng2-cookies'; 

@Injectable() 
export class AuthCookie { 
    constructor() { } 

    getAuth(): string { 
     return Cookie.get('id_token'); 
    } 

    setAuth(value: string): void { 
     //0.0138889//this accept day not minuts 
     Cookie.set('id_token', value, 0.0138889); 
    } 

    deleteAuth(): void { 
     Cookie.delete('id_token'); 
    } 
} 

そして、あなたのコンポーネントインチ

if (!_this._authCookie.getAuth()) { 
    _this.router.navigate(["/login"]); 
    return false; 
} 
関連する問題