发送用户ID和access_token
问题说明
我正在使用React前端在ASP.NET Core 2.1应用中实现Auth0.
I'm implementing Auth0 in my ASP.NET Core 2.1 app with React front-end.
用户进行身份验证后,我会得到一个access_token
和一个id_token
.我很清楚access_token
的目的是授予对我的API方法的访问权限.我也了解id_token
提供了可以在前端应用程序中使用的用户数据.
Once the user authenticates, I get both an access_token
and an id_token
. I'm clear that the purpose of access_token
is to grant access to my API methods. I also understand that the id_token
provides user data which I can use in my front-end app.
问题/关注点是有关在进行API调用时将用户数据(例如userId
)发送到后端的问题.除了将userId
包含在我的POST
请求的正文中之外,还有其他方法可以将其发送到我的API方法吗?
The question/concern is about sending user data, such as userId
to my backend when I make API calls. Other than including userId
in the body of my POST
request, is there another way to send it to my API method?
在Auth0之前,我使用了其他一些解决方案,并且从它们那里收到的JWT token
总是包括userId
,username
等.我认为这是一种更安全的方法,因为即使有人可以看到在JWT token
中,签名使我们可以确保不对数据进行回火.
Prior to Auth0, I used a couple of other solutions and the JWT token
I received from them always included userId
, username
, etc. I thought this was a more secure approach because even though one can see what's in a JWT token
, the signature allows us to make sure the data is not temperered with.
即使我的API调用是通过SSL
保护的,但与通过JWT token
发送它相比,在我的请求正文中包含进行API调用的人的userId
还是不太安全.
Even though my API calls are secured through SSL
, I feel including the userId
of the person who's making the API call in the body of my request is less secure compared to sending it through a JWT token
.
我在这里遗漏了一些东西吗,还是我们确实通过常规方法在API调用中(即在POST
调用的正文中或在GET
调用的查询字符串中)通过常规方式发送了userId
?
Am I missing something here or do we indeed send the userId
through the regular means in an API call i.e. in the body of a POST
call or in the query string of a GET
call?
正确答案
很好的问题,我上周遇到了同样的问题,最后使用相同的JWTAccessToken
弄清楚了.
Good question man, i was going through the same problem last week and finally figured it out using the same JWTAccessToken
.
难点在于,在生成可在服务器中检索的访问令牌时,将经过身份验证的用户的 UserId 添加为声明.
The catch is in adding the UserId of the authenticated user as a claim when generating an access token which you can retrieve in the server.
添加声明以访问令牌
首先将用户的ID添加到您的声明列表中.
Add the user's id to your list of claims first.
List<Claim> claims = new List<Claim>();
claims.Add(new Claim("UserId", user.Id.ToString()));
然后生成访问令牌.
SecurityToken token = new JwtSecurityToken(
issuer: {YOUR_ISSUER},
audience: {YOUR_AUDIENCE},
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddMinutes(60),
signingCredentials: credentials
);
假设您已经知道如何在达到最终的代币生成之前执行这些步骤,这要从您在问题中所显示的oAuth
和JWT
的才能中扣除.
Am assuming you already know how to perform the steps before reaching this final token generation as deducted from your prowess of oAuth
and JWT
shown above in your question.
从访问令牌中检索版权声明
要从其access_token中读取 UserId ,我们创建几个帮助程序/扩展方法,以帮助我们从控制器的RequestContext
中读取access_token.
To read a UserId from their access_token, let's create a couple of helper/extension methods to help us in reading an access_token from the RequestContext
of a controller.
public static string GetUserId(this ControllerBase controller)
{
string securityKey = "{YOUR_SECURITY_KEY}";
SymmetricSecurityKey key = new SymmetricSecurityKey(new UTF8Encoding().GetBytes(securityKey));
JwtSecurityTokenHandler token_handler = new JwtSecurityTokenHandler();
var tokenValidationParams = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
ValidateLifetime = false
};
string bearer = controller.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer", string.Empty).Trim(' ');
List<Claim> claims = token_handler.ValidateToken(bearer, tokenValidationParams, out SecurityToken token).Claims.ToList();
Claim userClaim = claims.FirstOrDefault(x => x.Type == "UserId");
if(userClaim != null)
{
return userClaim.Value;
}
else
{
throw new Exception("Invalid AccessToken. UserId claim not found");
}
}
使用方法
现在让我们使用它来获取我们任意一个控制器中的 UserId :
Let's now use this to get the UserId in any of our controllers:
[Authorize]
public class ExampleController : Controller
{
public IActionResult Index()
{
string userId = this.GetUserId();
// --> continuing code goes here.
}
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfieca
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20