Sunday, March 29, 2015

Secure ASP.NET Web API with Windows Active Directory and Microsoft OWIN Components

If you are looking to secure your ASP.NET Web API using OWIN/Katana with just "plain old" Windows Active Directory, unfortunately, you will only find articles like the following on securing your application:

http://www.cloudidentity.com/blog/2013/12/10/protecting-a-self-hosted-api-with-microsoft-owin-security-activedirectory/

https://msdn.microsoft.com/en-us/magazine/dn463788.aspx

As you can tell from the above articles, these articles specifically address "Azure Active Directory"!

But if you want to secure your application with just standard Windows Active Directory, you won't find much guidance in that arena.

Fortunately, plugging in Windows Active Directory support into your OWIN/OAuth Pipeline is not that much more difficult than using standard Forms Authentication with Active Directory as I have outlined in my previous article: http://samirvaidya.blogspot.com/2015/03/aspnet-mvc-forms-authentication-with.html

The main element to take away from standard Forms Authentication is the use of the Membership API to validate your Active Directory User Credentials and plug it into the OWIN/OAuth Pipeline. 

Therefore, if you use a code sample from my earlier OAuth article references (http://samirvaidya.blogspot.com/2015/03/aspnet-web-api-owinkatana-and-jwt.html), you can simply modify the ValidateClientAuthentication method to include code such as the following:

public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)

{

    try

    {

        var username = context.Parameters["username"];

        var password = context.Parameters["password"];

 

        //Use the Active Directory Membership Provider to authenticate the user credentials

        if (Membership.ValidateUser(username, password))

        {

            context.OwinContext.Set("otc:username", username);

            context.Validated();

        }

        else

        {

            context.SetError("Invalid credentials");

            context.Rejected();

        }

    }

    catch

    {

        context.SetError("Server error");

        context.Rejected();

    }

    return Task.FromResult(0);

}

That is all there is to it!!




No comments:

Post a Comment