Search code examples
angularazurecookiesasp.net-coreantiforgerytoken

Antiforgery token not set in the cookie when deployed in azure


I have two app services, one is an angular app and the other is a .NET core 2.0 app. I create Antiforgery token from the latter and attach to a header for each request, so that it is set as a cookie in the former.

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);
    }

In Angular app withCredentials: true is set. This works in localhost but when deployed to azure cookies are not set in Chrome. In Microsoft Edge, cookies are displayed as the screenshot in the response but not in application storage.

enter image description here


Solution

  • We cannot access cookies from sub-domains where the top domain is azurewebsites.net since it is listed in public prefix list.

    Further details : ASP.NET5, MVC 6 Cookies not being shared across sites