HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Authenticating user/password against Active Directory using ASP.NET Identity

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
directoryidentityactiveuserpasswordagainstnetusingauthenticatingasp

Problem

I am trying to learn how to use ASP.NET Identity. My scenario is that I have to authenticate against Active Directory. For that purpose I am trying to use ActiveDirecotoryMembershipProvider.

What I have to do is:

  • Authenticate user/password against Active Directory



  • Check whether user is present in my own database



The way I did it is I configured in my web.config to use ActiveDirectoryMembershipProvider as default membership provider. Then I override PasswordSignInAsync method in my ApplicationSignInManager class (which inherits SignInManager) as follows:

public override Task PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
    var adok = Membership.Provider.ValidateUser(userName, password);
    if (adok)
    {
        var user = UserManager.FindByName(userName);
        if (user == null)
            return Task.FromResult(SignInStatus.Failure);
        else
        {
            base.SignInAsync(user, isPersistent, shouldLockout);
            return Task.FromResult(SignInStatus.Success);
        }
    }
    else
        return Task.FromResult(SignInStatus.Failure);
}


This seems to work, but I think it's not the right way to do it. Can anyone suggest any better way of achieving this?

Solution

SignInAsync is an async method, and you most likely want to wait for it to complete before returning the SignInStatus. In order to await it, we must declare the method with the async keyword. This also means we can simplify the return statements:

public override async Task PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
    if (Membership.Provider.ValidateUser(userName, password))
    {
        var user = UserManager.FindByName(userName);
        if (user == null)
        {
            return SignInStatus.Failure;
        }

        await base.SignInAsync(user, isPersistent, shouldLockout);
        return SignInStatus.Success;
    }

    return SignInStatus.Failure;
}

Code Snippets

public override async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
    if (Membership.Provider.ValidateUser(userName, password))
    {
        var user = UserManager.FindByName(userName);
        if (user == null)
        {
            return SignInStatus.Failure;
        }

        await base.SignInAsync(user, isPersistent, shouldLockout);
        return SignInStatus.Success;
    }

    return SignInStatus.Failure;
}

Context

StackExchange Code Review Q#90306, answer score: 3

Revisions (0)

No revisions yet.