Search code examples
c#web-servicesauthenticationiis-7.5

Extract BasicAuth username from Headers (C# WebService)


Pretty much as the title says, users log in using Basic auth over SSL and call a WebService method, I would like to extract the auth headers and use the username parameter in the method function. Is there an easy way to do this either inline (inside the Method itself), or as a Class method in a separate project?

.NET 4.5, IIS 7.5

Thanks

After some searching around I discovered some code that should do what I want:

string authHeader = WebClient.Headers[HttpRequestHeader.Authorization];

    if (authHeader != null && authHeader.StartsWith("Basic"))
    {
        Encoding encoding = Encoding.GetEncoding("iso-8859-1");
        string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
        string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
        int seperatorIndex = usernamePassword.IndexOf(':');
        return usernamePassword.Substring(0, seperatorIndex);
    }

But on compile Visual Studio errors with: An object reference is required for the non-static field, method, or property 'System.Net.WebClient.Headers.get'.

I know that once I can populate the authHeader string everything else will work as expected, but I am struggling with getting the actual header values.


Solution

  • Finally found the solution that worked for us, hopefully nobody sees any major problem with it, but if you do, please share it.

    private string username
        {
            get{
                HttpContext ctx = HttpContext.Current;
                string authHeader = ctx.Request.Headers["Authorization"];
                Encoding encoding = Encoding.GetEncoding("iso-8859-1");
                string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
                string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
                int seperatorIndex = usernamePassword.IndexOf(':');
                return usernamePassword.Substring(0, seperatorIndex);
            }
        }
    

    And that seems to solve our issue, we didn't want to send the username over separate to the headers, because it would allow someone to alter username parameter without it affecting the account they logon with, this way the account that they logon with is the the account we use to create our links, and it works.