发送用户 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
提供了我可以在我的前端应用程序中使用的用户数据。
question/concern 是关于在我进行 API 调用时向我的后端发送用户数据,例如 userId
。除了在我的 POST
请求正文中包含 userId
之外,还有其他方法可以将它发送到我的 API 方法吗?
在 Auth0 之前,我使用了其他几个解决方案,我从他们那里收到的 JWT token
总是包含 userId
、username
等。我认为这是一个更安全的方法方法,因为即使可以看到 JWT token
中的内容,签名也允许我们确保数据未被篡改。
尽管我的 API 通话是通过 SSL
保护的,但我觉得在我的请求正文中包括了拨打 API 的人的 userId
与通过 JWT token
.
发送相比安全性较低
我是不是遗漏了什么,或者我们确实在 API 调用中通过常规方式发送了 userId
,即在 POST
调用的正文中或在查询字符串中GET
电话?
问得好,我上周遇到了同样的问题,最后使用相同的 JWTAccessToken
解决了这个问题。
要点在于在生成可在服务器中检索的访问令牌时,添加经过身份验证的用户的 UserId 作为声明。
向访问令牌添加声明
首先将用户的 ID 添加到您的声明列表中。
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
的实力中扣除。
从访问令牌中检索声明
要从他们的 access_token 中读取 UserId,让我们创建几个 helper/extension 方法来帮助我们从中读取 access_token控制器的RequestContext
。
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:
[Authorize]
public class ExampleController : Controller
{
public IActionResult Index()
{
string userId = this.GetUserId();
// --> continuing code goes here.
}
}
我正在使用 React 前端在我的 ASP.NET Core 2.1 应用程序中实施 Auth0。
一旦用户通过身份验证,我就会同时获得 access_token
和 id_token
。我很清楚 access_token
的目的是授予对我的 API 方法的访问权限。我还了解到 id_token
提供了我可以在我的前端应用程序中使用的用户数据。
question/concern 是关于在我进行 API 调用时向我的后端发送用户数据,例如 userId
。除了在我的 POST
请求正文中包含 userId
之外,还有其他方法可以将它发送到我的 API 方法吗?
在 Auth0 之前,我使用了其他几个解决方案,我从他们那里收到的 JWT token
总是包含 userId
、username
等。我认为这是一个更安全的方法方法,因为即使可以看到 JWT token
中的内容,签名也允许我们确保数据未被篡改。
尽管我的 API 通话是通过 SSL
保护的,但我觉得在我的请求正文中包括了拨打 API 的人的 userId
与通过 JWT token
.
我是不是遗漏了什么,或者我们确实在 API 调用中通过常规方式发送了 userId
,即在 POST
调用的正文中或在查询字符串中GET
电话?
问得好,我上周遇到了同样的问题,最后使用相同的 JWTAccessToken
解决了这个问题。
要点在于在生成可在服务器中检索的访问令牌时,添加经过身份验证的用户的 UserId 作为声明。
向访问令牌添加声明
首先将用户的 ID 添加到您的声明列表中。
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
的实力中扣除。
从访问令牌中检索声明
要从他们的 access_token 中读取 UserId,让我们创建几个 helper/extension 方法来帮助我们从中读取 access_token控制器的RequestContext
。
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:
[Authorize]
public class ExampleController : Controller
{
public IActionResult Index()
{
string userId = this.GetUserId();
// --> continuing code goes here.
}
}