AngularApp 不返回 HttpOnly Cookie

时间:2021-06-02 12:38:15

标签: cookies httpcookie httponly

美好的一天,过去 3 天我一直在努力弄清楚为什么我没有收到我在验证用户以进行任何后续回复时设置的 HttpOnly cookie。我在这个网站上阅读了几篇文章,查看了文档,只是看不出问题是什么。我有一个 Angular 应用程序,它发送一个身份验证请求,该请求返回一个工作正常的 JWT 令牌,我将刷新令牌作为 HttpOnly cookie。这在响应头中返回就好了。我的理解是 HttpOnly cookie 应该出现在我为其编写了拦截器的任何后续请求中。

我已经阅读了大量关于为什么 localStorage 不是存储令牌的最佳主意,因此它在我的 angular 服务中。我想使用 HttpOnly cookie 来存储我的刷新令牌,它是长期存在的,因此不希望将其存储在浏览器的任何位置。我将非常感谢任何帮助为什么永远不会返回 cookie。

我的 Angular 应用在​​ localhost:4200 上运行,而我的 API 在 localhost:5000 上运行

这是 Startup.cs 中的 Asp Core 3.1 代码

配置方法:

app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors("AllowAllHeaders");

ConfigureServices 具有以下功能:

   services.AddCors(options =>
    {
        options.AddPolicy("AllowAllHeaders",
        builder =>
        {
            builder.WithOrigins("http://localhost:4200", "http://localhost:5000") 
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials();
        });
    });

我的 GetToken 方法的内容 - 这将返回有效负载并将 HttpOnly cookie 作为响应(如预期):

[HttpPost("gettoken")]
        public Object GetToken(UserCredentials userCredentials)
        {
            string key = "my_secret_key_12345"; //Secret key which will be used later during validation    
            var issuer = "localhost:5000";  //normally this will be your site URL    

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            //Create a List of Claims, Keep claims name short    
            var permClaims = new List<Claim>();
            permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            permClaims.Add(new Claim("role1", "poweruser"));

            //Create Security Token object by giving required parameters    
            var token = new JwtSecurityToken(issuer, //Issure    
                            issuer,  //Audience    
                            permClaims,
                            expires: DateTime.Now.AddDays(1),
                            signingCredentials: credentials);
            var jwt_token = new JwtSecurityTokenHandler().WriteToken(token);

            Response.Cookies.Append("X-Refresh-Token", "refreh token value", 
                new CookieOptions() { HttpOnly = true, Secure = false, SameSite = SameSiteMode.None });

        return new { success = true,  accessToken = jwt_token, user = "", navigationItems = "" };
    }

我的 Angular 拦截器:

if ( this._authService.accessToken && !AuthUtils.isTokenExpired(this._authService.accessToken) )
{
    newReq = req.clone({
        headers: req.headers.set('Authorization', 'Bearer ' + this._authService.accessToken),
        withCredentials: true
    });
}

上面的拦截器正确发送了授权令牌。我的问题是对 C# API 方法的任何后续调用都没有 HttpOnly cookie,据我所知,cookie 将被发回。 (注意:我计划最终使用 TLS 打开安全标志)

刷新令牌方法:Cookie 始终为空。

[HttpGet("refreshtoken")]
public string Refresh()
{
    var requestToken = HttpContext.Request.Cookies["X-Refresh-Token"];

    return requestToken;  //this value is always null  :-(
}

0 个答案:

没有答案
相关问题