Bohn
Bohn

Reputation: 26919

Test Credentials to access a web page

Is there a nice and tested piece of code out there that I can use for this purpose:

get the user/pass and the address of a web service (asmx page) and check if the user/pass are valid or not.

I think I should use HTTPRequest,etc to do that but I do not have a good knowledge on that topic , causing my current method to not working properly.

If there is a good piece of code for this purpose I appreciate for pointing me to that.

Thanks

P.S: I am not using DefaultCredentials in my code. Since I want them to enter user/pass so now I need to be able to TEST their user/pass and show proper message to them if their credentials is not valid.

Upvotes: 3

Views: 5527

Answers (2)

Jaroslav Jandek
Jaroslav Jandek

Reputation: 9563

You can use the HttpWebRequest.Credentials Property (depends on the web service authentication) and the CredentialCache Class.

Also some code examples (from google):
Retrieving HTTP content in .NET
Combine Invoking Web Service dynamically using HttpWebRequest with .Credentials.

Upvotes: 1

Ronnie Overby
Ronnie Overby

Reputation: 46480

public bool TestCredentials(string url, string username, string password)
{
    var web = new WebClient();
    web.Credentials = new NetworkCredential(username,password);

    try
    {   
        web.DownloadData(url);
        return true;
    }
    catch (WebException ex)
    {
        var response = (HttpWebResponse)ex.Response;
        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            return false;
        }

        throw;
    }   
}

Upvotes: 1

Related Questions