【发布时间】:2020-10-28 09:09:09
【问题描述】:
我有一个使用 JWT 身份验证并在登录时发出令牌的 API 项目。
我正在使用 ASP.NET 核心 MVC 项目作为客户端
在客户端应用程序中成功登录后,将返回一个 JWT 令牌, 现在我有了 JWT 令牌,
如何在我的客户端应用程序中访问 User.Identity?
我需要做什么才能在整个应用程序中获取和使用用户身份?
如何在客户端应用程序中管理授权?
API 项目
// configure strongly typed settings objects
var appSettingsSection = Configuration.GetSection("JwtSettings");
services.Configure<JwtSettings>(appSettingsSection);
// configure jwt authentication
var appSettings = appSettingsSection.Get<JwtSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidIssuer = appSettings.Issuer,
ValidAudience = appSettings.Audience,
ClockSkew = TimeSpan.Zero
};
x.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
登录端点
[HttpPost]
public ActionResult Login([FromBody] LoginViewModel user)
{
if (user == null)
{
return BadRequest("Invalid client request");
}
if (user.Email == "user@example.com")
{
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.Secret));
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var tokeOptions = new JwtSecurityToken(
issuer: appSettings.Issuer,
audience: appSettings.Audience,
claims: new List<Claim>(),
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddMinutes(30),
signingCredentials: signinCredentials
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
return Ok(new GenericResponse<string> { Data = tokenString, Message = null, Success = true });
}
else
{
return Unauthorized(new GenericResponse<string> { Data = null, Message = "Unauthorized", Success = false });
}
}
【问题讨论】:
-
有什么更新吗?我的回复对你有帮助吗?
-
@BrandoZhang 是的,有帮助,谢谢,发布了修改。
-
如果我的回复对您有帮助,请标记为回答。以便其他面临相同问题的人,您可以更轻松地找到答案。
标签: c# asp.net-mvc asp.net-core asp.net-web-api jwt