首页 > 解决方案 > 如何获取使用 http only cookie 保存的刷新令牌?

问题描述

我正在构建的 .net 核心应用程序由两部分组成。后端 API 和前端。我想使用 jwt 令牌进行身份验证。我在 Stackoverflow 上读到,最好将访问令牌保存到内存中,但将刷新令牌保存在安全且仅限 http 的 cookie 中。我已经完成了大部分配置,但我不明白如何将刷新令牌传递给前端(javascript 客户端)(页面刷新后)

我想也许我可以创建 ajax 请求,该请求会发送到控制器并从会话 cookie 中获取刷新令牌,但我不确定它是否正确。

我的问题是:如何将保存在 httponly 中的刷新令牌传递给前端 javascript?

标签: authenticationcookiesjwtasp.net-core-mvc

解决方案


更好的建议是将令牌保存到客户端。如果使用 session 来保存 token,那么在保存很多 token 时内存的大小是有限的。Jwt 身份验证有一个 cookie 配置,可以自动从 cookie 中获取。

   services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
            .AddCookie(config=>
            {
                config.Cookie.Name = "auth";
                config.Cookie.HttpOnly = true;//The cookie cannot be obtained by the front-end or the browser, and can only be modified on the server side
                config.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;//This cookie cannot be used as a third-party cookie under any circumstances, without exception. For example, suppose b.com sets the following cookies:
            })
        .AddJwtBearer(o =>
        {
            //...
        }

发送令牌或刷新令牌时,可以这样创建令牌。

  public IActionResult Authenticate()
    {
        //...
        var token = tokenHandler.CreateToken(tokenDescriptor);
        var tokenString = tokenHandler.WriteToken(token);
        Response.Cookies.Append("auth",tokenString);

        return Ok(tokenString);
    }

关于刷新令牌,只有在密钥相同的情况下,新令牌才会替换旧令牌。考虑使用 ajax,您可以将过期时间传递给客户端,并使用 javascript 添加监听事件。如果它会过期,您可以触发一个函数来使用 ajax 请求令牌。


推荐阅读