javascript - 如何在 Angular 2 中为 jwt token 设置 cookie

标签 javascript angular cookies

我正在尝试通过调用在成功时提供 JWT token 的快速 API 来验证来自 Angular 2 应用程序的用户。我有一个疑问需要澄清。

我们是要求 express 设置 cookie,还是 Angular 的工作是使用 token 设置 cookie

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

关于javascript - 如何在 Angular 2 中为 jwt token 设置 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43466159/

相关文章:

JavaScript Cookie 范围更改留下 2 个具有相同名称的 Cookie,但哪一个将被读取?

javascript - HTML5 音频不会在 Firefox 中播放第二次

javascript - 将动态数据传递给子组件

javascript - 我的 JS if 语句有问题吗?

angular - 如何在 ag-grid 中以编程方式更改 'no rows to show' 文本?

javascript - 使用 Angular 形式更改表单元素

javascript - 使 cookie 的查看变得整洁

java - IE 和 Chrome 的 Cookie 问题(使用 java)

javascript - 使用 Jquery.html() 时 Br 无法在 P 内部工作

javascript - 为什么 Javascript 程序员更喜欢在代码中为常量重复字符串而不是使用枚举类型对象?