setting cookies within a wcf service
Asked Answered
S

1

0

I have a asp mvc application consuming wcf rest services (all on the same box). For authentication calls, I am trying to set cookies inside a wcf rest service.

Code on the client side -

        HttpResponseMessage resp;
        HttpClient client = new HttpClient("http://localhost/auth/login/");
        resp = client.Get();

In the webservice I just use FormsAuthentication to set an authcookie.

        HttpCookie authCookie = FormsAuthentication.GetAuthCookie("foo", false);
        HttpContext.Current.Response.Cookies.Add(authCookie);

Assuming the credentials are hardcoded in the code - If I physically navigate to the browserpage

       http://localhost/auth/login 

(hard code credentials in the code) I can see that the authentication cookie is being set. However, if I just invoke it through code (as shown above) the authentication cookie is not being set.

Is there something obvious that I am overlooking here?

Spadiceous answered 28/3, 2011 at 18:32 Comment(0)
O
2

When you call the WCF service programatically the cookie it sets is stored in the HttpClient instance. The client browser never sees it so it is never set inside it. So you will need to set it manually:

using (var client = new HttpClient("http://localhost/auth/login/"))
{
    var resp = client.Get();
    // Once you get the response from the remote service loop
    // through all the cookies and append them to the response
    // so that they are stored within the client browser.
    // In this collection you will get all Set-Cookie headers
    // sent by the service, so find the one you need and set it:
    foreach (var cookie in result.Headers.SetCookie)
    {
        // the name of the cookie must match the name of the authentication
        // cookie as you set it in your web.config.
        var data = cookie["SomeCookieName"];
        Response.AppendCookie(new HttpCookie("SomeCookieName", data));
    }
}
Octavia answered 28/3, 2011 at 20:6 Comment(1)
Thanks Darin. That worked. Changing the name of the .aspxauth cookie to something else in the server caused it not to be set but that is another question...:)Spadiceous

© 2022 - 2024 — McMap. All rights reserved.