【发布时间】:2020-08-09 20:03:09
【问题描述】:
我想在 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"])
)
};
});
【问题讨论】:
-
want to authenticate users with JWT tokens in Asp.Net Core Web App (not WebAPI)你可以查看这个SO线程:stackoverflow.com/questions/37398276/…
标签: c# asp.net-core cookies jwt