Using Active Directory Authentication With Groups in ASP.NET MVC

I searched forever to find this, and it was one of those things where it is actually easy, buy maybe it’s so easy that no one bothers to write about it. I did find one post which helped a lot, but I don’t have the link right now. So, here are the steps to enable your ASP.NET MVC application to authenticate users automatically on the Intranet, using Kerberos, and using Active Directory groups:

Note: This is for MVC2. I believe MVC3 is exactly the same way. I was using VB at the time I wrote this, but obviously the C# version is similar.

1. Change your web.config as follows:
Add:
Remove any membership providers. In fact, you can remove the whole node.

2. Change your IIS configuration to enable Windows Authentication.
I also disabled all other authentication methods. Not sure if this is needed.

3. Add Authorize tags to the Controllers or Actions you want to secure. <Authorize(“Admins,Users”)> or [Authorize("Admins,Users")]

This attribute goes above the action or controller name.

That’s it! Make sure you use the “Windows 2000 Name” or whatever it is called, because apparently that’s now the provider matches group names.

You can also use logic in your views (including Master Pages) to control what the users see based on their role membership. There may be a better way, but I did it as follows:

  • <%= Html.ActionLink(“Unsecured Page”, “Index”, “Unsecured”)%>
  • <% If Page.User.IsInRole(“Group1″) OrElse Page.User.IsInRole(“Group2″) Then%>

  • <%= Html.ActionLink(“Product Admin”, “Index”, “Product”)%>
  • <%= Html.ActionLink(“Client Admin”, “Index”, “Client”%>
  • <% End If%>

    That way, the menu items only show up to the users who can actually access the page.

    Posted Wednesday, November 3rd, 2010 under ASP.NET MVC.

    Leave a Reply