How to retrieve Windows Active Directory information from .Net Core Web API

LAI TOCA
3 min readJul 25, 2019
Photo from https://www.udemy.com/active-directory-on-windows-server-2016-best-practices/

Using Windows Active Directory for users’ authentication and authorization was common technique under enterprise environment. Sometimes, we might want to identity a user in our application but don’t want reinventing the wheel ourselves. This article might help.

Here was simple example for getting user name for Active directory under the Web API through IIS.

Please enable WindowsAuthentication and disable AnonymousAuthentication from launchSettings.json

launchSettings.json

We could also double check the section <authentication> inside application host config under below path:

%HOMEPATH%\Documents\IISExpress\config\applicationhost.config

Also remember to execute API under IIS express or IIS, for the Kestrel light way server was not support for windows authentication and that means you would get null value return.

Running the sample application via Firefox and input AD relative account name and password (Just for the first time) from prompt windows then you could see AD name display on browser.

Input account name and password
Retrieved AD account back

Next, we would like to build up request from Postman for further testing, cause using browser was not easily for calling POST method and difficult to switch diversity environment (Development/QAS/Production).

Let’s simply create new request and naming as IIS_Auth and fired the request. Oops, something went wrong, we got status 401 Unauthorized return. Why?

401 Unauthorized

The root cause would be, we would like to use windows authentication for retrieving AD information but our request do not having permission yet. We could switch to tab of “Authorization” over Postman request window as below step.

Tab of Authorization
 (1) Select NTLM Authentication (Beta)
(2) Please don't tick "Yes, disable retrying the request"
(3) & (4) Typing your AD login user name and password

Then fire request again, now we are able to reach our web API:)

Response from web API

Someone might curious why we don’t check the checkbox above step (2). The simply reason was Postman will try to initiate authentication through several requests to get challenge or nonce and complete whole process. More detail please see this link.

Here was network packets if you got interested what postman did behind for us.

Ref: https://blogs.msdn.microsoft.com/benjaminperkins/2011/09/14/integrated-windows-authentication-with-ntlm/
Step (1) & (2)
Step (3) & (4)
Step (5) & (6)

Reference

--

--

LAI TOCA

Coding for fun. (Either you are running for food or running for being food.)