简体   繁体   English

如何找到使用jwt“登录”的当前用户的ID? 我正在尝试发出GET请求并按特定ID进行过滤

[英]How do I find the id of the current user that is “logged in” with a jwt? I am trying to make a GET request and filter by specific id

This the endpoint in my api that I am trying to access 这是我尝试访问的api中的端点

router.get('/:id', [jsonParser, jwtAuth], (req, res) => {
return Teams.find().sort({creator: req.params.id})
    .then(teams => res.status(200).json(teams))
    .catch(err => res.status(500).json({message: 'Internal server error'}));
});

The fetch will probably look something like this? 提取可能看起来像这样?

function viewProfile() {
const base = '/api/teams/';
const id = idFromJwt;
const url = base + id;

return fetch(url)
.then(res => res.json())
.then(response => {
//takes response and modifies DOM
    populateProfile(response);
})
.catch(err => console.log(err));
}

First of all, assuming you're using ExpressJS I do suggest leveraging express-jwt middleware to handle requests authentication and issuing new Tokens. 首先,假设您使用的是ExpressJS我建议您利用express-jwt中间件来处理请求身份验证和颁发新令牌。

What you need to bear in mind is that, you need to include the userId when you authenticate the user in the JWT payload in order to be able to retrieve it from the payload afterwards. 您需要记住的是,在JWT有效负载中对​​用户进行身份验证时,需要包括userId以便以后能够从有效负载中检索用户。

When user is authenticated, you have to store the token in the state of your application or in the localStorage or sessionStorage . 通过用户身份验证后,您必须将令牌存储在应用程序状态或localStoragesessionStorage

In case you want to decode the token on the front-end side and then send it to the API, you can use a simple module called jwt-decode to achieve that: 如果您想在前端对令牌进行解码,然后将其发送到API,则可以使用名为jwt-decode的简单模块来实现:

const jwtDecode = require("jwt-decode");
const token = window.localStorage.getItem("token"); // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWQiOiIxMjM0NTY3ODkiLCJpYXQiOjE1MTYyMzkwMjJ9.gHqSxzWpdOUL1nRAqUJg2CtjsEZZi8FLikD41i639zY
const tokenPayload = jwtDecode(token).id; // "123456789"

Please bear in mind that in case you decided to use express-jwt you need to also send the token in the headers of the request as authorization to authenticate. 请记住,如果您决定使用express-jwt还需要在请求的标头中发送令牌作为身份验证的authorization Hope it helps. 希望能帮助到你。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM