首页 > 解决方案 > 如何在 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"])
                )
            };
        });

标签: c#asp.net-corecookiesjwt

解决方案


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


推荐阅读