Keeping HTTP Basic Authentification alive while being redirected

后端 未结 2 768
旧时难觅i
旧时难觅i 2021-01-12 13:42

We are using web service with basic authentication. It all worked all fine, till owners of web service implemented balancing service. Which is simply redirects requests to

相关标签:
2条回答
  • 2021-01-12 14:29

    Follow the MSDN for HttpWebRequest.AllowAutoRedirect Property i found this :

    The Authorization header is cleared on auto-redirects and HttpWebRequest automatically tries to re-authenticate to the redirected location. In practice, this means that an application can't put custom authentication information into the Authorization header if it is possible to encounter redirection. Instead, the application must implement and register a custom authentication module. The System.Net.AuthenticationManager and related class are used to implement a custom authentication module. The AuthenticationManager.Register method registers a custom authentication module.

    Solution is to write a custom Authentication Module.

    Here what i've found about it :

    http://msdn.microsoft.com/en-us/library/system.net.authenticationmanager.aspx

    And here the AllowAutoRedirect properties page :

    http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.allowautoredirect.aspx

    UPDATE

    Can you try to use CredentialCache instead of add header to webrequest ?

    CredentialCache myCache = new CredentialCache();
    
    myCache.Add(
    new Uri("http://www.contoso.com/"),"Basic",new NetworkCredential(UserName,SecurelyStoredPassword));
    req.Credentials = myCache;
    
    0 讨论(0)
  • 2021-01-12 14:46

    Indeed, CredentialCache is working correctly. However, if you would like to add multiple basic auth credentials (for example if there is redirection that you are aware of) you can use following function that I have made:

    private void SetNetworkCredential(Uri uriPrefix, string authType, NetworkCredential credential)
    {
        if (request.Credentials == null)
        {
            request.Credentials = new CredentialCache();
        }
    
        if (request.Credentials.GetCredential(uriPrefix, authType) == null)
        {
            (request.Credentials as CredentialCache).Add(uriPrefix, authType, credential);
        }
    }
    

    I hope it will help somebody in the future.

    0 讨论(0)
提交回复
热议问题