【问题标题】:Antiforgery token not set in the cookie when deployed in azure在 azure 中部署时未在 cookie 中设置防伪令牌
【发布时间】:2019-05-13 04:12:42
【问题描述】:

我有两个应用服务,一个是 Angular 应用,另一个是 .NET core 2.0 应用。我从后者创建 Antiforgery 令牌并附加到每个请求的标头,以便在前者中将其设置为 cookie。

Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddAntiforgery(options =>
        {
            options.HeaderName = "X-XSRF-TOKEN";
            options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            options.Cookie.HttpOnly = false;
            options.Cookie.SameSite = SameSiteMode.None;

        });
        ...

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseCookiePolicy(new CookiePolicyOptions
        {
            MinimumSameSitePolicy = SameSiteMode.None
        });

        app.UseAntiforgeryTokenMiddleware("X-XSRF-TOKEN");
        ....

AntiForgeryMiddleware.cs

    public async Task Invoke(HttpContext context, IAntiforgery antiforgery, ILogger<AntiForgeryMiddleware> logger)
    {
        string path = context.Request.Path.Value;
        if (path != null && path.ToLower().Contains("/api/account/authorizeview"))
        {
            if (httpVerbs.Contains(context.Request.Method, StringComparer.OrdinalIgnoreCase))
            {
                var tokens = antiforgery.GetAndStoreTokens(context);

                context.Response.Cookies.Append(requestTokenCookieName, tokens.RequestToken, new CookieOptions()
                {
                    HttpOnly = false, 
                    Secure = true
                });
            } 
        }
        context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");

        await next.Invoke(context);
    }

在 Angular 应用程序中设置了 withCredentials: true。 这在 localhost 中有效,但在部署到天蓝色 cookie 时未在 Chrome 中设置。在 Microsoft Edge 中,cookie 在响应中显示为屏幕截图,但不在应用程序存储中。

【问题讨论】:

    标签: angular azure cookies asp.net-core antiforgerytoken


    【解决方案1】:

    我们无法从顶级域为 azurewebsites.net 的子域访问 cookie,因为它已列在公共前缀列表中。

    更多详情:ASP.NET5, MVC 6 Cookies not being shared across sites

    【讨论】:

    • 我的响应标头中有这个Access-Control-Allow-Origin: site-address Access-Control-Allow-Credentials: true ,但cookie 仍然没有在客户端设置,你找到解决办法了吗?
    猜你喜欢
    • 1970-01-01
    • 2020-04-27
    • 2020-07-09
    • 2018-02-04
    • 2013-05-25
    • 2017-03-08
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多