webclient NetworkCredential not working with localhost in network domain

0 votes
asked Jul 15, 2015 in Other by anonymous

I am trying to get a forms auth cookie from a url using the my domain credential in my office network. When I used the url on the internet explorer, it says, I am authorized. But programmatically I am trying to get Forms Auth cookie from the Forms auth cookie url. Iam using Webclient and I am passing NetworkCredential including my domain name. But I am getting the exception as "The remote server returned an error: (401) Unauthorized". Am I missing anything here?

using (var client = new WebClientEntended())
{

    if (String.IsNullOrEmpty(user) && String.IsNullOrEmpty(password))
    {
        client.UseDefaultCredentials = true;
    }
    else
    {
        client.Credentials = new NetworkCredential(user, password, "domain");
    }

    client.DownloadString(FormsAuthentication.LoginUrl);
    var cookies = client.CookieContainer.GetCookies(new Uri(FormsAuthentication.LoginUrl));
    foreach (var ckie in cookies)
    {
        if (ckie.ToString().Contains(FormsAuthentication.FormsCookieName))
        {
            authCookie = (Cookie)ckie;
            CacheHelper.SetValue(string.Format("{0}{1}", user, FormsAuthentication.FormsCookieName),
                authCookie, OneDay);
            return true;
        }
    }
}
Share

1 Answer

0 votes
answered Jul 15, 2015 by Aadhira (1,213 points)
selected Jul 15, 2015 by administrator
 
Best answer

I think sometime the client application may not be able to negotiate the authentication type with the Internet service. So you may need to specify the authentication type as "NTLM". Please try the below code in your else condition and see if it works. I has this same issue and it worked for me. Thanks.

var credentialCache = new CredentialCache
{
    {
        new Uri(FormsAuthentication.LoginUrl), "NTLM",
        new NetworkCredential(user, password, "domain")
    }
};
client.Credentials = credentialCache;

Your answer

Preview

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2015 pinfaq.com
...