如何在Angular 8中存储jwt令牌之类的数据?还有使用本地存储或会话存储安全存储的另一种方法吗? [英] How to store data like jwt token in Angular 8? Is there another way to store safely using localstorage or session storage?

查看:227
本文介绍了如何在Angular 8中存储jwt令牌之类的数据?还有使用本地存储或会话存储安全存储的另一种方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JWT令牌来授权来自angular 8网站的对我的API的请求.但是我在哪里存储对用户不可见的令牌?我尝试使用服务,但刷新页面令牌后丢失.

I am using JWT tokens to authorise requests to my API from an angular 8 website. But where do i store this token which is not visible to user? i have tried using Service but after refresh page token gets lost.

推荐答案

您可以使用Cookie来存储令牌,而不是使用本地存储或会话存储,但这并不能确保其安全.即使加密cookie或本地存储,也不是一种防呆机制,因为加密密钥既可以驻留在客户端,也可以从服务器传递.这使得它很容易被修改.

You can make use of cookies to store the token instead of the local storage or session storage however thats not going to make it secure. Even encrytping the cookies or local storage isnt a fool-proof mechanism as the key for encryption would either reside on client side or passed from a server. Which makes it susceptible to modification.

为实现处理令牌的安全机制,建议您查看

For implementing a secure mechanism of handling your token I suggest you have a look at this answer

要替代本地存储或会话存储,可以按以下方式使用Cookie:

For having an alternative to local storage or session storage you can use cookies as follows:

您可以安装此软件包 https://www.npmjs.com/package/ng2-饼干

然后,您只需执行以下步骤

Then you can simply follow the steps

import { Cookie } from 'ng2-cookies/ng2-cookies';

//setter for token
Cookie.set('jwtToken', 'tokenValue');
//getter for token
let token = Cookie.get('jwtToken');
//delete token cookie
Cookie.delete('jwtToken');

或者您可以为Angular 4及更高版本安装 NGX Cookie服务

Or you can install NGX Cookie Service for version Angular 4 and above

安装

npm install ngx-cookie-service --save

导入并注入您的组件

import { CookieService } from 'ngx-cookie-service';
export class AppComponent implements OnInit {


  constructor( private cookieService: CookieService, private _authService: AuthService ) { }

  ngOnInit(): void {
    //call your auth service to get the token, I have made a call to a dummy auth service to fetch the token
    var token = _authService.GetToken();
    //Set auth token cookie
    this.cookieService.set( 'authToken', token );
    //get auth token cookie
    this.cookieValue = this.cookieService.get('authToken');
  }
}

这篇关于如何在Angular 8中存储jwt令牌之类的数据?还有使用本地存储或会话存储安全存储的另一种方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆