【问题标题】:Save jwt to local storage将 jwt 保存到本地存储
【发布时间】:2018-11-05 06:08:55
【问题描述】:

我目前正在开发一个 node express postgresql 应用程序,并且我正在尝试将 Jsonwebtokens 实现为身份验证。我看过多个关于如何实现它的教程,并且我知道如何在后端部分执行它,但是通常会跳过前端,显然每个人都只是用 Postman 测试他们的代码。

我也在网上看到,推荐的实现 jwt 身份验证的方法是将生成的令牌存储在 localstorage 中,并在需要时将其发送到 header 中。但我无法找到这是如何完成的......

因此,我的问题是:

  1. 令牌由后端生成后,如何将其存储在前端? (一个例子会有很大帮助,因为我真的不明白我应该如何在前端 javascript 程序上获取令牌)
  2. 在发出需要存储令牌的 http 请求时,如何在标头上发送令牌?

【问题讨论】:

标签: node.js authentication jwt frontend pugjs


【解决方案1】:

如您所说,通常令牌存储在 localStorage 中。

localStorage 与 sessionStorage 类似,不同之处在于 while 数据 存储在localStorage没有过期时间,数据存储在 sessionStorage 在页面会话结束时被清除——也就是说,当 页面已关闭。
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

为了在前端获取令牌,您将用户的电子邮件和密码发送到 URL,以便与令牌​​交换(您必须在 https 中)。之后,您将其存储为 localStorage.setItem('key', value)

简短示例:

$.post("/authenticate", {email: userEmail, password: userPassword}, function(data) {
  localStorage.setItem('token', data.token)
});

要取回令牌,例如刷新后,您必须使用:localStorage.getItem('key')

最后,为了使用此令牌进行身份验证,您可以在 Authorization headers 属性中的不记名头中发送它。
为什么是承载? => https://security.stackexchange.com/questions/108662/why-is-bearer-required-before-the-token-in-authorization-header-in-a-http-re

例子:

$.ajax({
    type: 'GET',
    url: '/account,
    headers: {
        "Authorization": "Bearer " + token
    }
}, function(data) { 
    // Authenticated data
});

这可能会有所帮助:https://github.com/auth0-blog/angularjs-jwt-authentication-tutorial/blob/master/frontend/login/login.js

【讨论】:

  • 您在回答中给出的示例是在 AJAX 请求上设置 http 标头,但是这可以在单击导航栏链接时设置标头吗?或者在提交表单时?非常感谢您的回答!它帮助我将令牌存储在本地存储中!现在我只需要弄清楚如何在需要时发送它......
  • @Juan 你有想过这个吗?目前仍在尝试弄清楚如何发送令牌。
  • @Scott 不太明白...我最终使用了 cookie,因为在提交表单时我无法从本地存储发送令牌。在标头中发送 cookie 并在服务器端读取它是非常标准的,之后我就没有问题了。
  • @Juan 是的,我自己也使用了相同的解决方案!
【解决方案2】:

在服务器端,一旦您创建了令牌并登录用户,您就可以通过 res.send() 发送令牌,例如下面的示例,请注意您可能对函数 findByCredentials 和 generateAuthToken 有不同的方法,它们是自定义的:

app.post("/users/login", async (req, res) => {
  try {
    const user = await User.findByCredentials(
      req.body.email,
      req.body.password
    );
    const token = await user.generateAuthToken();

    res.send({ token: user.tasks });
  } catch (e) {
    res.status(400).send();
  }
});

在前端,您可以使用 html5 的 fetch() 在标头中发送令牌。例如,如果您想访问需要身份验证的“/users/me”,请按照以下步骤操作(但请确保先将令牌保存到本地存储,以便您可以通过 getItem 访问它:

localStorage.setItem('userInfo', JSON.stringify(userInfo));

document.getElementById("my-profile").addEventListener("click", getMe);

然后:

function getMe(e) {
    e.preventDefault();
    var token = JSON.parse(localStorage.getItem('token'));
    console.log(`Authorization=Bearer ${token}`)
    fetch('/users/me', {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer ' + token
        }
    })
        .then(res => res.json())
        .then(data => {
            console.log(data)
            // window.location.href = 'http://localhost:3000/dashboard';
        })
        .catch(err => { console.log(err) })
} 

【讨论】:

    猜你喜欢
    • 2018-11-12
    • 2018-11-14
    • 2016-04-29
    • 2021-12-06
    • 2014-07-07
    • 2022-01-23
    • 2018-11-20
    • 2017-09-22
    相关资源
    最近更新 更多