locked
How to use basic http authentication in c#? RRS feed

  • Question

  • how can i use basic http Authentication for a HTTPS URL Windows 8 Store App. I am using Visual Studio 2012, C# and XAML.

    Is there any point to keep attention when i use an HTTPS URL?

    i have tried these following methods:

    private async void HttpClientCall(object sender, RoutedEventArgs e)
        {
    
            System.Diagnostics.Debug.WriteLine(this.GetType().Name + ": test");
    
    
            // Create a client
            HttpClient httpClient = new HttpClient();
    
            // Assign the authentication headers
            httpClient.DefaultRequestHeaders.Authorization = CreateBasicHeader("username", "password");
    
            // Call out to the site
            HttpResponseMessage response = await httpClient.GetAsync("https://urlHERE");
    
            // Just as an example I'm turning the response into a string here
            string responseAsString = await response.Content.ReadAsStringAsync();
    
        }
    
        public AuthenticationHeaderValue CreateBasicHeader(string username, string password)
        {
            password = SampleHashMsg("MD5", password);
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(username + ":" + password);
            System.Diagnostics.Debug.WriteLine("AuthenticationHeaderValue" + new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)));
            return new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
        }
    
        public String SampleHashMsg(String strAlgName, String strMsg)
        {
            // Convert the message string to binary data.
            IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(strMsg, BinaryStringEncoding.Utf8);
    
            // Create a HashAlgorithmProvider object.
            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName);
    
            // Demonstrate how to retrieve the name of the hashing algorithm.
            String strAlgNameUsed = objAlgProv.AlgorithmName;
    
            // Hash the message.
            IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);
    
            // Verify that the hash length equals the length specified for the algorithm.
            if (buffHash.Length != objAlgProv.HashLength)
            {
                throw new Exception("There was an error creating the hash");
            }
    
            // Convert the hash to a string (for display).
            String strHashBase64 = CryptographicBuffer.EncodeToHexString(buffHash);
    
            // Return the encoded string
            return strHashBase64;
        }

    i just want to display a HTTPS website where authentication is needed. i am getting a Warning from visual studio and it stop working:

    An error occurred while sending the request.

    A first chance exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.dll

    Monday, October 21, 2013 3:00 PM

Answers

  • Ideally speaking you should not be ignoring server certificate errors and instead look at resolving them. To identify what the security error is, you can navigate to the same website using IE, check the certificate error and then try to rectify it.

    Using the old System.Net.Http.HttpClient class you will not be able to bypass the certificate errors, but if you are targeting your app to run on Windows 8.1, you can use the Windows.Web.Http.HttpClient class to bypass certificate errors. This blog covers the details: http://blogs.msdn.com/b/wsdevsol/archive/2013/10/17/how-to-ignore-self-signed-certificate-errors-in-windows-store-apps-8-1.aspx

    But, again, you should not be just bypassing server certificate errors and instead try to rectify them.


    Windows Store Developer Solutions, follow us on Twitter: @WSDevSol|| Want more solutions? See our blog

    Tuesday, October 22, 2013 5:21 PM
    Moderator
  • The fundamental solution is to update that server's certificate.  Until that happens, you and your customer might think that you are "encrypted" and "secure" -- but you aren't.

    Microsoft has a strong recommendation that all code that overrides basic SSL security provide an opt-in dialog to users (IIRC, this is what the Mail app does when it works against Exchange servers with self-signed certs). 

    Recommended reading: The Most Dangerous Code in the World : it's an easy + scary read on real-word security issues.

    That said, here's what to do:

    1. Make the request
    2. On failure, pop up the error dialog
    3. On customer acceptance, set the minimal set of flags in HttpBaseProtocolFilter.IgnorableServerCertificateErrors
    4. Retry the request

    Thanks to the pipelined filter model of Windows.Web.Http, you should create a small 'filter' to actual do this; that way your top-level app doesn't even need to know that you've popped up an error dialog, making your app business logic much simpler.   In addition, having only one bit of code that dangerously allows unsafe SSL means that your code audits will be easier, too.

    We have a poster showing the overall flow of the Windows.Web.Http filter pipeline and the family of classes.  Download the HttpClient poster here


    Network Developer Experience Team (Microsoft)

    Tuesday, October 22, 2013 5:29 PM

All replies

  • The code doesn't look wrong, however, what is the actual Exception you are receiving? What URL are you trying to hit? Does it repro with only external websites or your internal websites too?

    Windows Store Developer Solutions #WSDevSol || Want more solutions? See our blog, http://aka.ms/t4vuvz

    Monday, October 21, 2013 6:47 PM
    Moderator
  • That code doesn't look grossly wrong; I've just quickly converted it to the Windows.Web.Http HttpClient code, changing the AuthenticationHeaderValue to an HttpCredentialsHeaderValue object and passing in Uri instead of a string to the GetAsync().  That worked OK (albeit, I didn't try against a service that actually requires username/password)

    If you need to visualize the entire Windows.Web.Http HttpClient family of classes, we have a poster available for download at http://www.microsoft.com/en-us/download/details.aspx?id=40018


    Network Developer Experience Team (Microsoft)

    Monday, October 21, 2013 7:58 PM
  • Thats all of Exception. THe error is the certificate on the HTTPS server, it is outdated. Is there a way to skip/ignore the certificate?

    "Could not establish trust relationship for SSL/TLS secure channel....The remote certificate is invalid according to the validation procedure."

    Any idea?

    Tuesday, October 22, 2013 10:01 AM
  • Ideally speaking you should not be ignoring server certificate errors and instead look at resolving them. To identify what the security error is, you can navigate to the same website using IE, check the certificate error and then try to rectify it.

    Using the old System.Net.Http.HttpClient class you will not be able to bypass the certificate errors, but if you are targeting your app to run on Windows 8.1, you can use the Windows.Web.Http.HttpClient class to bypass certificate errors. This blog covers the details: http://blogs.msdn.com/b/wsdevsol/archive/2013/10/17/how-to-ignore-self-signed-certificate-errors-in-windows-store-apps-8-1.aspx

    But, again, you should not be just bypassing server certificate errors and instead try to rectify them.


    Windows Store Developer Solutions, follow us on Twitter: @WSDevSol|| Want more solutions? See our blog

    Tuesday, October 22, 2013 5:21 PM
    Moderator
  • The fundamental solution is to update that server's certificate.  Until that happens, you and your customer might think that you are "encrypted" and "secure" -- but you aren't.

    Microsoft has a strong recommendation that all code that overrides basic SSL security provide an opt-in dialog to users (IIRC, this is what the Mail app does when it works against Exchange servers with self-signed certs). 

    Recommended reading: The Most Dangerous Code in the World : it's an easy + scary read on real-word security issues.

    That said, here's what to do:

    1. Make the request
    2. On failure, pop up the error dialog
    3. On customer acceptance, set the minimal set of flags in HttpBaseProtocolFilter.IgnorableServerCertificateErrors
    4. Retry the request

    Thanks to the pipelined filter model of Windows.Web.Http, you should create a small 'filter' to actual do this; that way your top-level app doesn't even need to know that you've popped up an error dialog, making your app business logic much simpler.   In addition, having only one bit of code that dangerously allows unsafe SSL means that your code audits will be easier, too.

    We have a poster showing the overall flow of the Windows.Web.Http filter pipeline and the family of classes.  Download the HttpClient poster here


    Network Developer Experience Team (Microsoft)

    Tuesday, October 22, 2013 5:29 PM