Skip to content

Instantly share code, notes, and snippets.

@jhalbrecht
Created June 15, 2012 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhalbrecht/2934558 to your computer and use it in GitHub Desktop.
Save jhalbrecht/2934558 to your computer and use it in GitHub Desktop.
I used this code over https to do basic authentication from wp7 to mvc 4 beta with web api
// I used this article to get the headers right.
// http://cisforcoder.wordpress.com/2010/12/01/how-to-implement-basic-http-authentication-in-wcf-on-windows-phone-7/
// The commented out NetworkCredential that I had tried earlier didn't work.
// I wonder if there is a better way to do this in Mango?
//
// Would like to learn to use asp.net membership with web api from the phone and metro.
// this works for now.
private void btnTest_Click(object sender, System.Windows.RoutedEventArgs e)
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new
DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
//NetworkCredential credentials =
// new NetworkCredential(settings.Login, settings.Password);
//client.Credentials = credentials;
var credentials = EncodeBasicAuthenticationCredentials(settings.Login, settings.Password);
client.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " + credentials;
client.DownloadStringAsync(new Uri(@"https://www.TheSiteIHaveItOn.com/api/Sounds"));
}
private string EncodeBasicAuthenticationCredentials(string username, string password)
{
//first concatenate the user name and password, separated with :
string credentials = username + ":" + password;
//Http uses ascii character encoding, WP7 doesn’t include
// support for ascii encoding but it is easy enough to convert
// since the first 128 characters of unicode are equivalent to ascii.
// Any characters over 128 can’t be expressed in ascii so are replaced
// by ?
var asciiCredentials = (from c in credentials
select c <= 0x7f ? (byte)c : (byte)'?').ToArray();
//finally Base64 encode the result
return Convert.ToBase64String(asciiCredentials);
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Debug.WriteLine(e.ToString());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment