Jerrold
Jerrold

Reputation: 1564

Forms Authentication on Windows Phone 7.1 (Mango)?

I'm trying to logon to my works website using WP7 (Mango) emulator using forms authentication. (Eventually create a WP7 app that lets you view some things on this site)

The sites webconfig contains this:

  <system.web.extensions>
<scripting>
    <webServices>
        <authenticationService enabled="true" requireSSL="false"/>
    </webServices> 
</scripting>

They have sample code that basically logs in by calling an authentication ODataService, passing in the user/pass and getting back an authentication cookie.

With this cookie all new requests include it to the ODataService, and should be able to retrieve data.

Before any requests are made - get authentication cookie

private static string GetAuthenticationCookie(string username, string password)
    {
        if (authenticationCookie == null)
        {
            string loginServiceAddress = websiteUrl + "/Authentication_JSON_AppService.axd/Login";

            var request = CreateAuthenticationRequest(username, password, loginServiceAddress);

            var response = request.GetResponse();
            if (response.Headers["Set-Cookie"] != null)
            {
                authenticationCookie = response.Headers["Set-Cookie"];
            }
            else
            {
                throw new SecurityException("Invalid credentials");
            }
        }

        return authenticationCookie;
    }       

private static WebRequest CreateAuthenticationRequest(string username, string password, string loginServiceAddress)
    {
        var request = HttpWebRequest.Create(loginServiceAddress);

        request.Method = "POST";
        request.ContentType = "application/json";
        var body = string.Format(
            "{{ \"userName\": \"{0}\", \"password\": \"{1}\", \"createPersistentCookie\":false}}",
            username,
            password);
        request.ContentLength = body.Length;

        var stream = request.GetRequestStream();
        using (var sw = new StreamWriter(stream))
        {
            sw.Write(body);
        }

        return request;
    }

I cant just copy-paste this code into the Windows Phone 7.1 (Mango) app, as the networking code is slightly different - for example..everything is done asynchronously in WP7 and something like

myWebRequest.GetResponse()

no longer works..and i have to do something like

myWebRequest.BeginGetResponse()

If anyone has any working code samples that authenticates using forms auth in WP7 - that would be great

Thanks much

Upvotes: 3

Views: 575

Answers (1)

Rico Suter
Rico Suter

Reputation: 11858

Check out this http class:

http://mytoolkit.codeplex.com/wikipage?title=Http

The following code should do the trick:

private void OnButtonClick(object sender, RoutedEventArgs e)
{
    const string username = "user";
    const string password = "password";
    const string loginServiceAddress = "http://www.server.com/Services/AuthenticationService.svc";

    var text = string.Format("{{ \"userName\": \"{0}\", \"password\": \"{1}\", \"createPersistentCookie\":false}}", 
        username, password);

    var request = new HttpPostRequest(loginServiceAddress);
    request.RawData = Encoding.UTF8.GetBytes(text);
    request.ContentType = "application/json";
    Http.Post(request, AuthenticationCompleted);
}

private void AuthenticationCompleted(HttpResponse authResponse)
{
    const string serviceAddress = "http://www.server.com";
    if (authResponse.Successful)
    {
        var sessionCookie = authResponse.Cookies.Single(c => c.Name == "SessionId");
        var request = new HttpGetRequest(serviceAddress);
        request.Cookies.Add(new Cookie("SessionId", sessionCookie.Value));
        Http.Get(request, OperationCallCompleted);
    }
}

private void OperationCallCompleted(HttpResponse response)
{
    if (response.Successful)
    {
        // TODO: do your parsing
        var responseText = response.Response;

        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            // TODO: set data to binding or directly to user control (in UI thread)
        });
    }
}

Upvotes: 2

Related Questions