2

I have been fighting with this nonsense for too long. I have read multiple articles and have seen plenty of Stackoverflow questions, but still cannot find a definitive answer.

From what I have read, a response to an ajax request can contain a "Set-Cookie" header which in turn is accepted by the browser. On subsequent requests to the same domain, the browser is supposed to send the cookie back to the server. (Assuming they are on the same domain).

First of all, is the above correct, or have I misunderstood something?

Second, assuming this is correct, what am I missing from my application below? I started a new Empty asp.net project in Visual Studio 2015 and had it add the components for WEB API. I then made the following controller:

public class AuthenticationController : ApiController
{
    [Route("api/Authentication/Login/")]
    [HttpPost]
    public HttpResponseMessage Login([FromBody]CredentialContainer credentials)
    {
        var response = new HttpResponseMessage();

        try
        {
            var token = Guid.NewGuid().ToString(); 
            var cookie = new CookieHeaderValue("access_token", token);

            cookie.Expires = DateTimeOffset.Now.AddDays(1);
            cookie.Domain = Request.RequestUri.Host;
            cookie.Path = "/";
            cookie.HttpOnly = true;

            response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
            response.StatusCode = HttpStatusCode.OK;

            return response;
        }
        catch (Exception ex)
        {
            response.StatusCode = HttpStatusCode.InternalServerError;
            return response;
        }
    }

    [Route("api/Authentication/DoSomething")]
    [HttpGet]
    public IHttpActionResult DoSomething()
    {
        var cookie = Request.Headers.GetCookies();
        return Ok();
    }
}

public class CredentialContainer
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

In the same project I added a single HTML page with some simple JavaScript to call out to the WEB API.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<button onclick="login()">LogIn</button>
<button onclick="doSomething()">DoSomething</button>
<script>
    function login() {
        var xhr = new XMLHttpRequest();
        var data = { UserName: "user", Password: "password" };

        xhr.open("POST", "http://localhost/WebApplication1/api/Authentication/Login/", true);
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.withCredentials = true; 
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    alert(document.cookie); 
                }
                else {
                    alert("Fail"); 
                }
            }
        }

        xhr.send(JSON.stringify(data));  
    }

    function doSomething() {
        var xhr = new XMLHttpRequest();

        xhr.open("GET", "http://localhost/WebApplication1/api/Authentication/DoSomething/", true);
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.withCredentials = true;
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                var response = xhr.response;
            }
        }

        xhr.send();
    }
</script>

This web application is being hosted on my local IIS (NOT IIS Express). When I click the login button, a response is returned to the client that includes a "Set-Cookie" header. I have verified this with Fiddler. The browser, however, ignores this. Whenever I make a request back via the "doSomething()" method, the cookie is not sent back. I have verified this with Fiddler and in the DoSomething() Web API method.

I know by setting the HttpOnly = true, JavaScript can't access the cookie, so document.cookie is going to be blank, but I don't see why that would stop the browser sending it on subsequent requests. I am at my wit's end with this stuff. Can someone please shed some light on the problem or point me to a working .NET example that actually sends cookies on a request?

Thank you

Dave
  • 2,473
  • 2
  • 30
  • 55

1 Answers1

2

Ok, figured out the problem is with using localhost. The answer provided by Sire for this question solved my problem.

Why won't asp.net create cookies in localhost?

Community
  • 1
  • 1
Dave
  • 2,473
  • 2
  • 30
  • 55