c# - 如何在 Asp Net Core Web App(不是 WebAPI)中存储令牌
问题描述
我想在 Asp.Net Core Web App(不是 WebAPI)中使用 JWT 令牌对用户进行身份验证。如何存储 JWT 令牌,将其发布在每个 Http 请求的标头中,以及如何在控制器操作中从 cookie 中读取存储的信息?
这是我在 Auth 控制器中的登录方法:
[HttpPost]
[Route("LoginStudent")]
public async Task<IActionResult> PostLoginStudent(StudentLoginDto loginDto)
{
if (!ModelState.IsValid)
{
return RedirectToAction(
actionName: "GetLoginStudent",
routeValues: new { error = "Invalid login credentials." }
);
}
// Result is instance of a class which contains
// - content (StudentReturnDto) of response (from Repository),
// - message (from Repository),
// - bool IsSucces indicates whether operation is succes.
var result = await _repo.LoginStudent(loginDto);
if (result.IsSuccess)
{
// User must be Authorized to acces this Action method.
return RedirectToAction("GetProfile");
}
// If it fails return back to login page.
return RedirectToAction(
"GetLoginStudent",
routeValues: new { error = result.Message }
);
}
[HttpGet]
[Authorize]
public IActionResult GetProfile()
{
// Reading user id from token
return View();
}
在启动类中,我配置了这样的身份验证:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidateAudience = true,
ValidIssuer = _config["Jwt:Issuer"],
ValidAudience = _config["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_config["Jwt:Key"])
)
};
});
解决方案
事实证明,在网络应用程序中,建议使用 cookie 作为身份验证方法。但是如果你想使用 JWT,你仍然应该将 token 保存在 cookie 中。然后,从 cookie 中读取令牌并验证它。感谢 Fei Han,这个帖子解释了这个话题。
推荐阅读
- php - 唯一验证在 Laravel 中不起作用
- python - 为什么当我使用 pandas 从网站上抓取表格时,它会跳过中间列,只打印前 2 和最后 2
- perl - 通过 perl 5 读取文本文件中的数据
- css - SVG 占主导地位的基线和小坐标系
- javascript - 如果某些链接包含关键字并在新选项卡中打开它们,Chrome 扩展程序可以从页面中获取某些链接
- kubernetes - 为什么 kubectl 不要求输入密码?
- python - 制作美国热图?
- java - 硒脚本未运行
- python - Python 在不应该出现的情况下进入文件的下一行
- jpa - JPA 存储库在保存后检索自定义主键值