繁体   English   中英

如何在Angular 2中为jwt令牌设置cookie

[英]How to set a cookie for jwt token in Angular 2

我正在尝试通过调用在成功时提供JWT令牌的Express API来从Angular 2应用验证用户身份。 我有一个疑问要清除。

我们要求Express设置cookie还是用标记设置cookie是Angular的工作?

    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);
        })
    }

您需要使用Angular来完成。 是的,您可以使用建议的localStorage,但最好使用Cookie

这是我在angular2应用程序中使用过的代码示例。

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');
    }  
}

并且在您的组件中,您可以使用以下几行来验证AuthCookie。

if (!_this._authCookie.getAuth()) {
    _this.router.navigate(["/login"]);
    return false;
}

您必须使用Angular来做。 我个人使用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()));
}

暂无
暂无

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

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