Search code examples
asp.net-web-apiwindows-store-appswindows-8.1winrt-httpclient

Windows.Web.Http.HttpClient + WEB API Windows Authentication


Im using Windows.Web.Http.HttpClient to connect to my WEB API. Application haven't prompted for userid and password, but recently i changed WEB API by moving AuthorizeAttribute filter from Action to Class level. Now my Windows store 8.1 application prompt for user id and password. Please let me know how to set HttpClient to not prompt the login and password. Can any1 suggest me do i need to add header to my httpcleint

using (Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient()) { // Add a user-agent header var headers = httpClient.DefaultRequestHeaders;

// The safe way to check a header value from the user is the TryParseAdd method // Since we know this header is okay, we use ParseAdd with will throw an exception // with a bad value - http://msdn.microsoft.com/en-us/library/windows/apps/dn440594.aspx

                headers.UserAgent.ParseAdd("ie");
                headers.UserAgent.ParseAdd("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");


                using (var response = await httpClient.GetAsync(new Uri(url)))

I dont see a way to send Default credentials.


Solution

  • Disable UI dialogs using HttpBaseProtocolFilter.AllowUI. Try this:

    Windows.Web.Http.Filters.HttpBaseProtocolFilter filter =
        new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
    filter.AllowUI = false;
    HttpClient client = new HttpClient(filter);
    
    Uri uri = new Uri("http://localhost/?basic=1");
    var response = await client.GetAsync(uri);
    System.Diagnostics.Debug.WriteLine(response);
    

    Do you need credentials? Use HttpBaseProtocolFilter.ServerCredential. Try this:

    Uri uri = new Uri("http://localhost?ntlm=1");
    
    Windows.Web.Http.Filters.HttpBaseProtocolFilter filter =
        new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
    filter.AllowUI = false;
    
    // Set credentials that will be sent to the server.
    filter.ServerCredential =
        new Windows.Security.Credentials.PasswordCredential(
            uri.ToString(),
            "userName",
            "abracadabra");
    
    HttpClient client = new HttpClient(filter);
    var response = await client.GetAsync(uri);
    System.Diagnostics.Debug.WriteLine(response);
    

    Do you need default Windows credentials (domain credentials)? Simply add the Enterprise Authentication capability to your Package.appxmanifest.