Vítor Martins
Vítor Martins

Reputation: 1440

How to Implement Active Directory Authentication in ASP.NET Web API Through Forms?

I've been reading a lot of guides/articles but haven't found one yet that does exactly what I want... that is to implement Active Directory Authentication in an ASP.NET Web API through forms.

Something like on this guide:

Cool MVC 5 guide to implement authentication with Active Directory

Which is very good but it's for MVC, i.e., it uses a Controller not an ApiController

Can someone please give me hints/tips/articles on how to start? Especially about the part that connects to the active directory. I've been stuck on this for a while.

UPDATE:

public bool IsAuthenticatedUser(string srvr, string usr, string password)
       {
           bool authenticated = false;

           try {
               DirectoryEntry entry = new DirectoryEntry(srvr, usr, password);
               object nativeObject = entry.NativeObject;
               Object obj = entry.NativeObject;
               authenticated = true;
           }
           catch {
               throw new HttpResponseException(HttpStatusCode.Unauthorized);
           }
           return authenticated;
       }

       // POST: api/Login
       public void Post([FromBody]string username, [FromBody]string password)
       {
           if (IsAuthenticatedUser("LDAP string", username, password))
           {
               Redirect("Index");
           }
           else
           {
               throw new HttpResponseException(HttpStatusCode.Unauthorized);
           }
       }

I was thinking of trying something like this for the authentication, your thoughts?

Upvotes: 2

Views: 3026

Answers (1)

Alexander
Alexander

Reputation: 1263

Well, I don't think it's correct to make FORMS authentication for WebApi. The sense of WebApi is working with data in RESTful manner.

So my suggestion is (if you want to use AD FORMS authentication):

1) Create test environment to test AD authentication - for this purpose, you may use Oracle VirtualBox. On it, you want to install Windows Server 2016 (evaluation for 180 days), where you build AD, create domain and add some test users to it, install AD SSL certificate (hand-made is OK);

2) Install the certificate from 1) on host machine for SSL connections between host and virtual PCs (since you gonna send plain credentials);

3) In your Web Application, you make traditional MVC login page, using SSL cookie to store credential information: you create this cookie in your Authenticate controller method. The process of authentication is as simple as writing correct connection string in web.config for System.Web.Security.ActiveDirectoryMembershipProvider, checking user validity is an ordinary Membership.ValidateUser method;

4) Once the user is successfully validated, use the saved cookie to validate the user between inner WebApi requests

Upvotes: 1

Related Questions