【发布时间】:2018-07-20 07:25:41
【问题描述】:
我在我的 ASP.NET Core 2 Web API 项目中使用 JWT 令牌
我的前端 Web 客户端发送一个 JWT 令牌,它最初从 Web API 登录 API 获得,每个请求都能正常工作。但是,我也有一个离线客户端,它使用相同的 API 并最初在线登录,然后存储 JWT 离线发送,仅当用户同步应用程序时才发送它,这可能是一周后。令牌可能已过期或服务器 Web 应用程序在此期间重新启动。
如果 JWT 令牌由于离线客户端过期而失败,我仍然希望访问 Web API 控制器方法并填充 ASP.NET Identity User 对象,因为我需要用户名。我将记录此事件,但我也需要过期/无效令牌中的用户名。目前,如果身份验证失败,将不会输入控制器方法,因此我添加了一个 [AllowAnonymous] 属性,但这将导致 User.Identity 在我想要用户名的地方为空
我的代码:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication()
.AddJwtBearer(cfg =>
{
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = _config["Tokens:Issuer"],
ValidAudience = _config["Tokens:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]))
};
});
当用户登录时
private IActionResult CreateToken(ApplicationUser user, IList<string> roles)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
_config["Tokens:Issuer"],
_config["Tokens:Audience"],
claims.ToArray(),
expires: DateTime.Now.AddMinutes(60),
signingCredentials: creds);
var results = new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo,
};
return Created("", results);
我确保在经过身份验证后,各种 API 调用都会传递 JWT 令牌。
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class MyController : Controller
{
这使我可以使用以下代码捕获登录用户以进行各种 API 调用
var loggedInUser = User.Identity.Name;
如果 JWT 令牌已过期或无效,我如何读取用户名?
【问题讨论】:
标签: asp.net-core jwt asp.net-core-webapi