将jwt保存到本地存储

时间:2018-05-25 19:54:21

标签: node.js authentication jwt frontend pugjs

我目前正在开发一个节点表达postgresql应用程序,我正在尝试将Jsonwebtokens实现为身份验证。我已经看过关于如何实现它的多个教程,我在后端部分得到了如何做,但是前端通常被跳过,显然每个人都只是用Postman测试它们的代码。

我还在网上看到,实现jwt身份验证的推荐方法是将生成的令牌存储在localstorage中,并在需要时将其发送到头部。但我无法找到这是怎么做的......

因此,我的问题是:

  1. 如果后端生成令牌,如何将令牌存储在前端? (一个例子会有很多帮助,因为我真的不知道如何在前端javascript程序上获取令牌)
  2. 如果在存储了需要它的http请求后,如何在标头上发送令牌?

2 个答案:

答案 0 :(得分:0)

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

  

localStorage类似于sessionStorage,除了数据   存储在localStorage中没有到期时间,数据存储在   sessionStorage在页面会话结束时清除 - 也就是说,何时清除   页面已关闭。
  https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

要在前端获取令牌,您需要向网址发送电子邮件&用户的密码,以便与令牌​​交换(您必须使用https)。之后,您将其存储为localStorage.setItem('key', value)

简短的例子:

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

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

最后,为了使用此令牌进行身份验证,您可以在Authorization标头属性中的承载标头中发送它。
为何选择? => 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

答案 1 :(得分:0)

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

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) })
} 
相关问题