Home > OS >  ASP.NET controller not always appending cookies
ASP.NET controller not always appending cookies

Time:07-07

I've written a controller in asp.net that appends a token cookie after login. When I do the get call directly in the browser to the controller the cookie gets appended and can subsequently be read in request.cookies afterwards. However, when I make the same call from my blazor view page to the same controller using the same parameters the login process in the controller still works (showing that the call was made correctly) but after doing response.cookies.append the cookie count is still 0 on subsequent request reads.

Both the controller and the view page are running from localhost with the controller on https and the view page on http. (these will be secured in the future but I'm testing functionality in UAT, also the basic auth return is only for diagnostic reasons at the moment to make sure encoding and decoding was working correctly)

Here is the controller code:

[HttpGet("/Login")]
    public String Get(String Email, String Pass)
    {
        String token = null;
        token = Auth.Login(Email, Pass);
        if (token != null)
        {
            String basicauth = Convert.ToBase64String(Encoding.ASCII.GetBytes(Email ":" token));
            CookieOptions cookieOptions = new CookieOptions();
            cookieOptions.IsEssential = true;
            cookieOptions.SameSite = SameSiteMode.Lax;
            cookieOptions.Secure = false;
            Response.Cookies.Append("bearer",basicauth,cookieOptions);
            Console.WriteLine("Cookie count after login: "   Request.Cookies.Count);
            return basicauth;
        }
        return "token was null";
    }

The code for testing the stored cookie is below: (which is returning null only from the view page, not for direct get calls in the browser. Request.cookies.count gives a similar 1 and 0 response respectively)

public class ValidateCookieToken : ControllerBase
{

    [HttpGet("/ValidateCookie")]
    public String Get()
    {
        String bearertoken;
        Console.WriteLine("ValidateCookies current cookie count: "   Request.Cookies.Count);
        Console.WriteLine("Validatecookies cookie keys: "   Request.Cookies.Keys);
        Request.Cookies.TryGetValue("bearer", out bearertoken);
        String decodedbearer = Encoding.ASCII.GetString(Convert.FromBase64String(bearertoken));
        return decodedbearer;
    }
}

Edit: I've now added the withCredentials:true header on my browser side requests which now shows the cookie in the header on requests; however, the response still doesn't have the cookie header even though I've set the below CORS policies and applied to my get controllers.

builder.Services.AddCors(options =>
    {
    options.AddPolicy("CookiePolicy",
    policy =>
    {
        policy.WithOrigins("http://localhost:5196","https://localhost:7139").AllowCredentials().AllowAnyHeader();
    });

    options.AddPolicy("AnotherPolicy",
    policy =>
    {
    policy.WithOrigins("http://www.contoso.com")
    .AllowAnyHeader()
        .AllowAnyMethod();
    });
    });

CodePudding user response:

Cookies will not be included by default in cross origin requests in Browsers, so you need to explicitly allow it.

var requestMessage = new HttpRequestMessage
{
  ...               
};
            
requestMessage.SetBrowserRequestOption("credentials", "include");

You can read more about that option here - https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials.

  • Related