10

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

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

因此,我的问题是:

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

2 回答 2

3

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

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) })
} 
于 2019-05-10T00:28:28.883 回答
1

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

localStorage 与 sessionStorage 类似,不同之处在于,虽然 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')

最后,为了使用此令牌进行身份验证,您可以将其发送到Authorizationheaders 属性中的不记名标头中。
为什么是承载?=> 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

于 2018-05-25T20:55:33.797 回答