发送用户 ID 和 access_token [英] Sending user Id along with access_token
问题描述
我正在使用 React 前端在我的 ASP.NET Core 2.1 应用程序中实现 Auth0.
一旦用户通过身份验证,我就会得到一个 access_token
和一个 id_token
.我很清楚 access_token
的目的是授予对我的 API 方法的访问权限.我也了解 id_token
提供了我可以在前端应用中使用的用户数据.
问题/担忧是关于在我进行 API 调用时将用户数据(例如 userId
)发送到我的后端.除了在我的 POST
请求正文中包含 userId
之外,还有其他方法可以将其发送到我的 API 方法吗?
在 Auth0 之前,我使用了一些其他解决方案,我从他们那里收到的 JWT 令牌
总是包括 userId
、username
等. 我认为这是一种更安全的方法,因为即使可以看到 JWT 令牌
中的内容,但签名允许我们确保数据没有被调和.
尽管我的 API 调用是通过 SSL
保护的,但我觉得在我的请求正文中包含进行 API 调用的人的 userId
相比之下安全性较低通过 JWT 令牌
发送.
我是否在这里遗漏了什么,或者我们确实通过 API 调用中的常规方式发送了 userId
,即在 POST
调用的正文中或在查询字符串中GET
调用?
好问题的人,我上周遇到了同样的问题,最后使用相同的 JWTAccessToken
解决了这个问题.
问题在于,在生成可以在服务器中检索的访问令牌时,将经过身份验证的用户的 UserId 添加为声明.
向访问令牌添加声明
首先将用户的 ID 添加到您的声明列表中.
List声明 = 新列表<声明>();claim.Add(new Claim("UserId", user.Id.ToString()));
然后生成访问令牌.
SecurityToken token = new JwtSecurityToken(发行人:{YOUR_ISSUER},观众:{YOUR_AUDIENCE},索赔:索赔,notBefore: DateTime.UtcNow,过期:DateTime.UtcNow.AddMinutes(60),签名凭据:凭据);
假设您已经知道如何在达到最终令牌生成之前执行这些步骤,这从您在问题中上面显示的 oAuth
和 JWT
的实力中扣除.>
从访问令牌中检索声明
要从其 access_token 中读取 UserId,让我们创建几个帮助器/扩展方法来帮助我们从控制器的 RequestContext
中读取 access_token.>
public static string GetUserId(这个ControllerBase控制器){string securityKey = "{YOUR_SECURITY_KEY}";SymmetricSecurityKey key = new SymmetricSecurityKey(new UTF8Encoding().GetBytes(securityKey));JwtSecurityTokenHandler token_handler = new JwtSecurityTokenHandler();var tokenValidationParams = 新的 TokenValidationParameters{ValidateAudience = 假,ValidateIssuer = 假,ValidateIssuerSigningKey = true,IssuerSigningKey = 密钥,验证生命周期 = 假};string bearer = controller.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer", string.Empty).Trim(' ');列表<声明>claim = token_handler.ValidateToken(bearer, tokenValidationParams, out SecurityToken token).Claims.ToList();声明 userClaim = claim.FirstOrDefault(x => x.Type == "UserId");如果(用户索赔!= null){返回 userClaim.Value;}别的{throw new Exception("Invalid AccessToken. UserId claim not found");}}
如何使用
现在让我们使用它来获取任何控制器中的 UserId:
[授权]公共类 ExampleController :控制器{公共 IActionResult 索引(){string userId = this.GetUserId();//-->继续代码在这里.}}
I'm implementing Auth0 in my ASP.NET Core 2.1 app with React front-end.
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.
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?
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.
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
.
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?
Good question man, i was going through the same problem last week and finally figured it out using the same JWTAccessToken
.
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.
Adding Claims To Access Token
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()));
Then generate an access token.
SecurityToken token = new JwtSecurityToken(
issuer: {YOUR_ISSUER},
audience: {YOUR_AUDIENCE},
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddMinutes(60),
signingCredentials: credentials
);
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.
Retrieve Claim From 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");
}
}
How To Use
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.
}
}
这篇关于发送用户 ID 和 access_token的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!