[英]Sending user Id along with access_token
I'm implementing Auth0 in my ASP.NET Core 2.1 app with React front-end. 我正在使用React前端在ASP.NET Core 2.1应用程序中实现Auth0。
Once the user authenticates, I get both an access_token
and an id_token
. 用户认证后,我将同时获得一个
access_token
和一个id_token
。 I'm clear that the purpose of access_token
is to grant access to my API methods. 我很清楚
access_token
的目的是授予对我的API方法的访问权限。 I also understand that the id_token
provides user data which I can use in my front-end app. 我也了解
id_token
提供了可以在前端应用程序中使用的用户数据。
The question/concern is about sending user data, such as userId
to my backend when I make API calls. 问题/关注点是有关在进行API调用时将用户数据(例如
userId
发送到后端的问题。 Other than including userId
in the body of my POST
request, is there another way to send it to my API method? 除了在
POST
请求的主体中包含userId
,还有另一种方法可以将其发送到我的API方法吗?
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. 在Auth0之前,我使用了其他一些解决方案,并且从它们那里收到的
JWT token
始终包含userId
, username
等。我认为这是一种更安全的方法,因为即使可以看到JWT token
,签名也可以我们确保数据不会受到控制。
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调用是通过
SSL
保护的,但与通过JWT token
发送相比,在我的请求正文中包含进行API调用的人员的userId
仍然不那么安全。
Am I missing something here or do we indeed send the userId
through the regular means in an API call ie in the body of a POST
call or in the query string of a GET
call? 我是否在这里丢失了某些信息,还是我们确实通过常规方式在API调用中(即在
POST
调用的正文中或在GET
调用的查询字符串中)发送了userId
?
Good question man, i was going through the same problem last week and finally figured it out using the same JWTAccessToken
. 好问的人,我上周遇到了同样的问题,最后使用相同的
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. 要注意的是,在生成可以在服务器中检索到的访问令牌时,将经过身份验证的用户的UserId作为声明添加。
Adding Claims To Access Token 添加声明以访问令牌
Add the user's id to your list of claims first. 首先将用户ID添加到您的声明列表中。
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. 假设您已经从问题中上面显示的
oAuth
和JWT
能力中扣除了,那么在达到最终令牌生成之前,您已经知道如何执行这些步骤。
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. 要从其access_token读取UserId ,让我们创建几个帮助器/扩展方法,以帮助我们从控制器的
RequestContext
读取access_token。
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: 现在让我们使用它在我们的任何控制器中获取UserId :
[Authorize]
public class ExampleController : Controller
{
public IActionResult Index()
{
string userId = this.GetUserId();
// --> continuing code goes here.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.