Validate credentials against AD

Might be a brainfart but, whenever i try to validate my credentials in my webform against ad it always returns true(approved), why is that? This is just a test to make sure its working whenever i click the "submit" button:

protected void Button1_Click(object sender, EventArgs e)
    {
        string username1 = uniloginTextBox.Text;
        string password1 = passwordTextBox.Text;

        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "cv.local"))
        {
            // validate the credentials
            bool isValid = pc.ValidateCredentials(username1, password1, ContextOptions.Negotiate);
        }

        if (IsValid == true)
        {
            Label.Text = "approved";
        }
        else if (IsValid == false)
        {
            Label.Text = "Denied";
        }

Upvotes: 2

Views: 804

Answers (1)

Equalsk
Equalsk

Reputation: 8224

Your if statement is checking the truth value of an object named IsValid. The bool you've created is named isValid. Notice one begins with a capital and the other does not.

The bool isValid won't exist outside of your using block as it's declared inside. Move isValid outside of the using statement like this:

protected void Button1_Click(object sender, EventArgs e)
{
    // Username and password text
    var username1 = uniloginTextBox.Text;
    var password1 = passwordTextBox.Text;

    // isValid defaults to false
    bool isValid = false;

    // Check credentials against AD
    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "cv.local"))
    {
        // Set value for isValid
        isValid = pc.ValidateCredentials(username1, password1, ContextOptions.Negotiate);
    }

    // Achieves the same as your if statement
    Label.Text = isValid ? "Approved" : "Denied";
}

Upvotes: 2

Related Questions