When you have an ASP.NET (.NET Framework) web application and you wish to use Active Directory groups as roles within the application it's not that difficult once you know how. Make sure your project uses Windows Authentication, if you didn't set this up when you started the project you can add it later.
Add this to your web.config file:
<system.web>
// Omitted for brevity
<authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
<providers>
<clear />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
// Omitted for brevity
</system.web>
The part with authentication mode
is already present when your project was made with Windows Authentication enabled.
What this snippet does is enabled you to use the AspNetWindowsTokenRoleProvider which allows your application to collect group memberships for your authenticated users. For more information of how to use this, look no further.
Now you can use Active Directory groups to allow or disallow usage of controllers within your application either by using the AuthorizeAttribute:
[Authorize(Roles = @"CONTOSO\MyGroup")]
public IHttpActionResult DoSomething()
{
// Todo
}
Or performing the checks yourself within the code of the controller:
public IHttpActionResult DoSomething()
{
var User = System.Web.HttpContext.Current.User;
if (User.IsInRole("CONTOSO\\MyGroup"))
{
// Todo
}
}
The Authorize
tag works with both MVC and Web API, however make sure to use the right namespaces. You need to use System.Web.Http
for Web API controllers and System.Web.Mvc
for MVC controllers. They are not compatible with each other, so don't mix them up.
Any groups you use for roles have to be security groups in Active Directory. Other kinds of groups like distribution lists will not work.