如何在 Asp Net Core Web App(不是 WebAPI)中存储令牌

Posted

技术标签:

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

【问题讨论】:

want to authenticate users with JWT tokens in Asp.Net Core Web App (not WebAPI)你可以查看这个SO线程:***.com/questions/37398276/… 【参考方案1】:

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

【讨论】:

以上是关于如何在 Asp Net Core Web App(不是 WebAPI)中存储令牌的主要内容,如果未能解决你的问题,请参考以下文章

将 ASP.Net Core Web App 项目发送给某人的最佳实践?

在 Asp.Net Core App 中访问 Web.config 设置?

如何对 asp.net core Blazor App 中的 oAuth 身份验证进行故障排除

Asp.net core 2.1 Web App 无法在 IIS 上正确呈现

使用ASP.NET CORE SignalR实现APP扫描登录

ASP.NET 4.5 在 ASP.NET Core 2.0 应用程序下的 Azure Web App 中将 502.5 作为虚拟应用程序抛出