【问题标题】:How to store token in Asp Net Core Web App (not WebAPI)如何在 Asp Net Core Web App(不是 WebAPI)中存储令牌
【发布时间】: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"])
                )
            };
        });

【问题讨论】:

标签: c# asp.net-core cookies jwt


【解决方案1】:

事实证明,在网络应用程序中,建议使用 cookie 作为身份验证方法。但是如果你想使用 JWT,你仍然应该将 token 保存在 cookie 中。然后,从 cookie 中读取令牌并验证它。感谢韩飞,this thread 解释了这个话题。

【讨论】:

    猜你喜欢
    • 2021-11-05
    • 2020-07-12
    • 1970-01-01
    • 2021-03-28
    • 2020-11-20
    • 1970-01-01
    • 2020-08-28
    • 2020-05-14
    • 1970-01-01
    相关资源
    最近更新 更多