[英]How do I better get current user id in Loopback
As the loopback.getCurrentContext()
has long-living unstability problems and deprecated currently, how can I make sure that when a user performs some operations via API endpoints, I know how to identify him? 由于loopback.getCurrentContext()
一直存在长期的不稳定问题,并且目前已弃用,我如何确保当用户通过API端点执行某些操作时,我知道如何识别他?
May be I can send the token id in the request payload and check it? 我可以在请求有效负载中发送令牌ID并进行检查吗? What if user fakes it? 如果用户伪造了该怎么办? What are alternatives to those hacky solutions from the issues page on Github? 在Github的问题页面上,那些骇人听闻的解决方案有哪些替代方案?
Check out https://docs.strongloop.com/display/public/LB/Making+authenticated+requests 查看https://docs.strongloop.com/display/public/LB/Making+authenticated+requests
In summary, once you've logged a user in it should give you back an AccessToken in the response. 总而言之,一旦您在其中登录了用户,就应该在响应中返回一个AccessToken。 You can then use that in the headers or on the query string to prove you're a logged in user: 然后,您可以在标题或查询字符串中使用它来证明您是登录用户:
# Authorization Header
curl -X GET -H "Authorization: $ACCESS_TOKEN" \
http://localhost:3000/api/widgets
# Query Parameter
curl -X GET http://localhost:3000/api/widgets?access_token=$ACCESS_TOKEN
This cannot easily be faked, as the access token is checked on each request to ensure it's current and valid. 这很容易被伪造,因为对每个请求都会检查访问令牌以确保它是最新和有效的。
Once you've done this, you can get at the accessToken via (taken from https://github.com/strongloop/loopback/issues/569#issuecomment-60924099 except attaching the user to the req object) 完成此操作后,您可以通过以下方式获取accessToken(取自https://github.com/strongloop/loopback/issues/569#issuecomment-60924099,但将用户附加到req对象除外)
app.use(function(req, res, next) {
app.currentUser = null;
if (!req.accessToken) return next();
req.accessToken.user(function(err, user) {
if (err) return next(err);
req.currentUser = user;
next();
});
});
Add this to your server.js
or a boot script and therefore have the user
object on ctx.req.currentUser
at any point. 将此添加到您的server.js
或启动脚本中,从而随时将user
对象放在ctx.req.currentUser
上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.