5

I'm trying to enable CORS on an existing asp.net web site which hosts several WCF services. Unfortunately, I'm having a hard time making it work. At first sight, I'm being redirected to the login page (which doesn't exist), so there probably is something wrong with the authentication cookie that is being generated by the custom authentication service.

Before going on, here's a simple description of the my current scenario:

  • I've got site A, which exposes several web services (all but the authentication service can only be accessed by authenticated users), and site B, which has a page that tries to interact with the web services
  • in order to replicate this scenario, I've put the services+the html page on the same place and I've created an alias (hosts file) in order to simulate the cors call (let's say I've called it outro.pt)
  • the authentication cookie is generated by using the FormsAuthentication.GetAuthCookie and then it's added to the response by calling the Response.AppendCookie method
  • authentication works as expected: first there's an OPTIONS call, followed by a POST call; when the second web service is called (POST again), there's no preflight check (because the first call ends up generating a Access-Control-Max-Age header in order to cache preflight checks for 5 mins), but the web site (outro.pt) ends up returning a 302 which redirects the browser to the login page.

    Before going on, here's the demo code used for handling the preflight and allowing cors calls (I've placed it within the app's beginrequest event):

    private void Application_BeginRequest(object sender, EventArgs e) {
        var ctx = HttpContext.Current;
    
        //allow credentials: always
        ctx.Response.AddHeader("Access-Control-Allow-Credentials", "true");
    
        //add allow origin header
        if (ctx.Request.Headers["Origin"] != null) {
            ctx.Response.AddHeader("Access-Control-Allow-Origin", ctx.Request.Headers["Origin"]);
        }
    
        if (ctx.Request.Headers["Access-Control-Request-Headers"] != null) {
            ctx.Response.AddHeader("Access-Control-Allow-Headers", ctx.Request.Headers["Access-Control-Request-Headers"]);
        }
    
        if (ctx.Request.HttpMethod.ToUpper() == "OPTIONS" ) {
            ctx.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
            //keep preflight info for 5 mins
            ctx.Response.AddHeader("Access-Control-Max-Age", (5 * 60).ToString());
            ctx.Response.End();
            return;
        }
    }
    

Now, here's the demo code for generating the authentication cookie (since this is demo code, I've opted for using a simple generic handler for it:

    public void ProcessRequest(HttpContext context) {
        context.Response.ContentType = "application/json";
        var name = "";
        using (var reader = new StreamReader(context.Request.InputStream)) {
            var std = (Student)JsonConvert.DeserializeObject(reader.ReadToEnd(),typeof(Student));
            name = std == null ? "" : std.name;
        }
        if (!String.IsNullOrEmpty(name)) {
            var cookie = FormsAuthentication.GetAuthCookie(name, false);              
            cookie.Domain = "outro.pt";
            context.Response.AppendCookie(cookie);
            context.Response.Write(JsonConvert.SerializeObject(new {valid = true}));
        }
        else {
            context.Response.Write(JsonConvert.SerializeObject(new { valid = false }));    
        }

    }

Now, after using fiddler, I can see that the cookie does get returned when the validation handler is called. for instance, here's an example of one cookie created by a call to the previous authentication handler:

Set-Cookie: .ASPXAUTH=1CB7EF39DBA39BDA2FD2AA0A0AAFDAB67821A286D04F1678C89CFD6036094A3F9C36D2C9E48FFE35B95C8A742F553138A8899E2CE63259F6DDC7A4D59868AF8A3F50EC037F1DAB73827B5D906A115C28FC8E4B744D661AF77592955F525E236D; domain=outro.pt; path=/; HttpOnly

At first sight, I can't see nothing wrong with this authentication cookie (I think that it's associated with the correct domain and it should be sent whenever I hit any page maitained within outro.pt, right? - even it it's placed inside another asp.net app like, say, outro.pt/demo/webservice.ashx?)

Since I was getting redirected to the login page when I tried to access the second web service, I though that the problem was that the authentication cookie was not being sent. And that's correct: according to fiddler, there's no cookies sent in the request headers for this second call. I've tried several things, but I can't manage to make it work.

After reading the docs, I think that setting the withCredentials field to true is the only required thing I need to do in order to send cookies, right? Btw, here's the second web service call which is performed by using jquery2:

    var complete = url + "studentservice.ashx";
    payload = {
                    url: complete,
                    type: 'POST',
                    xhrFields: {
                        withCredentials: true
                    },
                    contentType: 'application/json',
                    crossDomain: true,
                    dataType: 'json'
                };
    $.ajax(payload)
                    .done(function (data, status, xhr) {
                        alert("success");

                    })
                    .fail(function (xhr, status, error) {
                        alert("error" + error);
                    });

So, has anyone managed to use cors when the web services that need to be accessed require asp.net authentication? What am I missing?

thanks.

1 Answer 1

1

I think I've found the problem: the $.ajax method call for validating the user (and generating the cookie) didn't the withCredentials field, so the cookie returned from the server ended up being discarded.

3
  • Thanks for that. I have similar issue. Can you explain a little more? What method call was not passing the withCredentials field>? Sep 14, 2015 at 8:34
  • Sure. If I'm not mistaken, you need to add the xhrFields object to the $ajax call that performs the validation and authentication of the user. Using it only on subsequent requests (ie, requests performed after validation) won't work.
    – Luis Abreu
    Sep 15, 2015 at 10:29
  • OK thanks for that. I thought that is what you meant. Sep 15, 2015 at 10:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.