How to implement LDAP utility in APIcontroller of Web API in MVC4.0?
We must have used LDAP in our application frequently but I am sure most of the people are not aware of using same LDAP code in WEB API in MVC4.0
This code is for those who are new to WEB API and MVC4.0
You can use Microsoft Visual Studio 2012 to use WEB API template. You can create any internet application so that you can use it as a client.
What is LDAP ?
LDAP is Lightweight Directory Access Protocol used for accessing and maintaining distributed directory information services over an IP network.
Following steps can be followed -
1 Add reference of "System.DirectoryServices" to your project. This will allow you to use DirectoryEntry in your program.
2 You have to use following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.DirectoryServices;
namespace yournamespace.Controllers {
public class LoginController : ApiController {
public HttpResponseMessage Post(string domainname, string username, string pwd)
{
HttpResponseMessage message = new HttpResponseMessage();
if (ModelState.IsValid)
{
var companyurl = "LDAP://yourdomainnamewith.com";
String strcomplete = domainname + @"\" + username;
DirectoryEntry entry = new DirectoryEntry(companyurl, strcomplete, pwd);
try
{
DirectorySearcher StrSearchPerson = new DirectorySearcher(entry);
StrSearchPerson.Filter = "(SAMAccountName=" + username + ")";
StrSearchPerson.PropertiesToLoad.Add("cn");
SearchResult result = StrSearchPerson.FindOne();
if (null == result)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK, result, new
System.Net.Http.Headers.MediaTypeHeaderValue("application/Json"));
}
catch (HttpResponseException)
{ return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
else
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
}
Note - In above code, we have returned JSON that can be tested in WEB debugging tool for e.g. Fiddler.
How to test it through Fiddler?
You will find dropdown which has methods as GET , POST, PUT, DELETE. You have to use POST to test this, thenonly it goes in the above method at runtime because it checks for verb Post, if that matches then that method gets called.
You have to pass JSON in request body of Fiddler. Also You have to write correct content type while testing it in Fiddler. This way you can test web-api code without any front end. If you want to develop UI that is also feasible.
Further you can use HttpStatusCode returned by this method. If it is OK that means success else it throws bad request which is nothing but failure.
You can implement security mechanism like encrypting the passwords while passing it.