Home > Development, Web > HttpWebRequest Authentication error 400

HttpWebRequest Authentication error 400

Using .Net webrequest and webclient class with the default implementation of authentication may lead to error 400.
When the request URL contain querystring parameters .Net default implementing of authentication exclude the querystring parameters on authentication what should give error 400 by authentication definition

The solution is to implement by your self the authentication :

/// 
/// The function athenticate given WebRequest with given credentials
/// 
/// authenticating credentials
/// authenticated request
/// return response from first attempt to authenticate(relevant when no authentication was required or other error occur
/// true on success otherwise false
public bool AuthenticateRequest(ICredentials credentials, ref WebRequest webRequest, out WebResponse webResponse)
{
    webResponse = null;
    if (credentials == null)
    {
        return true;
    }
    if (webRequest == null)
    {
        throw new ArgumentNullException(@"webRequest");
    }
    try
    {
        webResponse = webRequest.GetResponse();
    }
    catch (WebException ex)
    {
        if ((ex.Status != WebExceptionStatus.ProtocolError) || (ex.Response == null) || (((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized))
        {
            throw;
        }

        string authenticateHeader = ex.Response.Headers[@"WWW-Authenticate"];
        if (string.IsNullOrEmpty(authenticateHeader))
        {
            throw new ApplicationException(@"No Authenticate Header");
        }

        IAuthenticateParams authenticateParams;
        if (!ExtractAuthenticateHeaderParametes(authenticateHeader, webRequest.RequestUri, out authenticateParams))
        {
            throw new ApplicationException(@"Failed to extract WWW-Authenticate header");
        }

        NetworkCredential credential = credentials.GetCredential(webRequest.RequestUri, authenticateParams.AthenticateType);
        if (credential == null)
        {
            throw new ApplicationException(@"Credential mismatch error");
        }

        IAuthenticationHandler authenicationHandler;
        if (!GetAuthenticationHandler(authenticateParams, out authenicationHandler))
        {
            throw new ApplicationException(@"Failed to get authentication handler");
        }

        string authorizationHeader;
        if (!authenicationHandler.GetAuthorizationHeader(credential, out authorizationHeader))
        {
            throw new ApplicationException(@"Failed to get authentication header"HttpWebRequest tmpRequest = (HttpWebRequest)webRequest;
        webRequest = (HttpWebRequest)WebRequest.Create(webRequest.RequestUri);
        webRequest.Headers[@"Authorization"] = authorizationHeader;
        ((HttpWebRequest)webRequest).UserAgent = tmpRequest.UserAgent;
        webRequest.ContentType = tmpRequest.ContentType;
    }

    return true;
}

Authentication Sample Code Download
Further explanation :
Http web request use several authentication types:
Basic
Digest
Ntlm

When web request is made to protected website an authentication request is made
The parameters are past in “WWW-Autherization” header, the parameters past in name equal value coma separated except authentication method which past as first string with no name value pattern
The client respond with the same request adding “authentication” header

When perform Digest authentication,
one of the parameters past is URL.
The URL parameter is past in both authentication header and mast be the same (rfc2617).
The URL parameter is the URL of the request without the host info,
for example, if the request is for www.abc.com/1.htm the parameter value will be /1.htm .
The problem with .Net default implementation is it removes query parameters so instead of passing /1.aspx?a=b it passes /1.aspx on the Authorization header.
That’s why the authentication fails.

  1. Tim
    January 30th, 2012 at 01:01 | #1

    Thank you, This is valuable information, you just save me some headache.. Thanks

  2. Wai Hojnacki
    February 2nd, 2012 at 02:08 | #2

    Thanks so much pertaining to giving me personally an update on this subject matter on your website. Please understand that if a brand-new post becomes available or when any modifications occur with the current submission, I would consider reading more and learning how to make good usage of those methods you write about. Thanks for your time and consideration of other folks by making this site available.

  3. Nir
    October 22nd, 2012 at 19:03 | #3

    Thanks for the super detailed post! You really helped me out.

  4. shade net manufactuers in vapi
    April 22nd, 2013 at 07:39 | #4

    hi!,I like your writing very so much! percentage we keep up a correspondence more approximately your post on AOL?
    I require a specialist in this space to resolve my problem.
    Maybe that’s you! Taking a look forward to peer you.

  5. April 3rd, 2016 at 11:04 | #5

    Nice post. I learn something new and challenging on websites I stumbleupon every day.
    It’s always interesting to read articles from other authors and use a little
    something from other sites.

  1. November 27th, 2011 at 14:42 | #1