I know that blog post title is sure a mouth-full, but it describes the whole problem I was trying to solve in a recent project.

The Project

Let me outline the project briefly.  We were building a report dashboard-type site that will live inside the client’s network.  The dashboard gives an overview of various, very important information that relates to how the company is performing on a hourly basis.  So, the dashboard is only available to a certain group of directors.

To limit the solution to the these directors, authentication and authorization would go through their existing Active Directory setup by putting the authorized users in a special AD group.

The Problem

Getting authentication to work was a snap.  Microsoft provides theSystem.Web.Security.ActiveDirectoryMembershipProvider
class to use as your membership provider.  Putting an [Authorize] attribute on my action methods or entire controllers was all I needed to get it working (besides, of course, the system.web/authentication web.config updates and a controller to show my login form and handle the submit credentials).

Here’s my relevant web.config setup:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<connectionStrings>
  <add name="ADConnectionString" connectionString="<ldap connection string here>" />
</connectionStrings>
...
<authentication mode="Forms">
  <forms name=".AuthCookie" loginUrl="~/login"/>
</authentication>
<membership defaultProvider="ADMembershipProvider">
  <providers>
    <clear/>
    <add name="ADMembershipProvider"
         type="System.Web.Security.ActiveDirectoryMembershipProvider"
         connectionStringName="ADConnectionString"
         attributeMapUsername="sAMAccountName"/>
  </providers>
</membership>

The tough part came when I wanted to limit access to users in that AD group. Microsoft doesn’t provide a RoleProvider along with its ActiveDirectoryMembershipProvider. So, what to do?

I tried several methods I found online. Most of them were based on creating my own customRoleProvider and querying AD to iterate through the user’s groups (treating them like roles) and seeing if one of them matched my AD group I was looking for. However, I could never get it to work. Each code example I found eventually gave me this AD error when I iterated through the current user’s AD groups:

1
The specified directory service attribute or value does not exist.

The Solution

Eventually, I found a solution online that worked. Instead of setting up a custom RoleProvider, all it involved was creating a custom AuthorizeAttribute for your MVC controllers (or action methods) that checked the user’s .IsMemberOf method to see if the member belonged the sought after group (or groups). I don’t know why this method does not cause the same AD error as describe above, but I’m glad it doesn’t! All I can assume is that it queries AD in a more friendly way.

Here is my custom AuthorizeAttribute:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class AuthorizeADAttribute : AuthorizeAttribute
{
    private bool _authenticated;
    private bool _authorized;
 
    public string Groups { get; set; }
 
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        base.HandleUnauthorizedRequest(filterContext);
 
        if (_authenticated && !_authorized)
        {
            filterContext.Result = new RedirectResult("/error/notauthorized");
        }
    }
 
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        _authenticated = base.AuthorizeCore(httpContext);
 
        if (_authenticated)
        {
            if (string.IsNullOrEmpty(Groups))
            {
                _authorized = true;
                return _authorized;
            }
 
            var groups = Groups.Split(',');
            string username = httpContext.User.Identity.Name;
 
            try
            {
                _authorized = LDAPHelper.UserIsMemberOfGroups(username, groups);
                return _authorized;
            }
            catch (Exception ex)
            {
                this.Log().Error(() => "Error attempting to authorize user", ex);
                _authorized = false;
                return _authorized;
            }
        }
 
        _authorized = false;
        return _authorized;
    }
}

Notice that I also included a little code to distinguish between the user not being authenticated (which the call to base.AuthorizeCore takes care of) and not being authorized. Without the code inHandleUnauthorizedRequest, if the user successfully logs in but is not in the AD group, he just sees the log in screen again which doesn’t communicate the problem very well.

The this.Log() code uses a Nuget packaged called this.Log. The LDAPHelper class is something I wrote. The code is below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public static class LDAPHelper
{
    public static string GetLDAPContainer()
    {
        Uri ldapUri;
        ParseLDAPConnectionString(out ldapUri);
 
        return HttpUtility.UrlDecode(ldapUri.PathAndQuery.TrimStart('/'));
    }
 
    public static string GetLDAPHost()
    {
        Uri ldapUri;
        ParseLDAPConnectionString(out ldapUri);
 
        return ldapUri.Host;
    }
 
    public static bool ParseLDAPConnectionString(out Uri ldapUri)
    {
        string connString = ConfigurationManager.ConnectionStrings["ADConnectionString"].ConnectionString;
 
        return Uri.TryCreate(connString, UriKind.Absolute, out ldapUri);
    }
 
    public static bool UserIsMemberOfGroups(string username, string[] groups)
    {
        /* Return true immediately if the authorization is not
        locked down to any particular AD group */
        if (groups == null || groups.Length == 0)
        {
            return true;
        }
 
        // Verify that the user is in the given AD group (if any)
        using (var context = BuildPrincipalContext())
        {
            var userPrincipal = UserPrincipal.FindByIdentity(context,
                                                 IdentityType.SamAccountName,
                                                 username);
 
            foreach (var group in groups)
            {
                if (userPrincipal.IsMemberOf(context, IdentityType.Name, group))
                {
                    return true;
                }
            }
        }
 
        return false;
    }
 
    public static PrincipalContext BuildPrincipalContext()
    {
        string container = LDAPHelper.GetLDAPContainer();
        return new PrincipalContext(ContextType.Domain, null, container);
    }
}

My code is mostly based on example code I found on a very helpful StackOverflow post:http://stackoverflow.com/questions/4342271/asp-net-mvc-forms-authorization-with-active-directory-groups/4383502#4383502.

To use this code, all you have to do is use your custom AuthorizeAttribute instead of the built-in one. Something like this:

1
2
3
4
5
[AuthorizeAD(Groups="Some AD group name")]
public class HomeController : Controller
{
...
}

Active Directory Authentication in ASP.NET MVC 5 with Forms Authentication and Group-Based Authorization的更多相关文章

  1. Forms Authentication in ASP.NET MVC 4

    原文:Forms Authentication in ASP.NET MVC 4 Contents: Introduction Implement a custom membership provid ...

  2. [转]Implementing User Authentication in ASP.NET MVC 6

    本文转自:http://www.dotnetcurry.com/aspnet-mvc/1229/user-authentication-aspnet-mvc-6-identity In this ar ...

  3. Asp.Net MVC 身份验证-Forms

    Asp.Net MVC 身份验证-Forms 在MVC中对于需要登录才可以访问的页面,只需要在对应的Controller或Action上添加特性[Authorize]就可以限制非登录用户访问该页面.那 ...

  4. Migrating an ASP.NET MVC application to ADFS authentication

    I recently built an ASP.NET application at work to help track internal use of our products. It's bee ...

  5. 简化 Web 应用程序与 Windows Azure Active Directory、ASP.NET 和 Visual Studio 的集成

    大家好! 今天的博文深入讨论我们今天推出的开发人员工具和框架中的一些新功能.我们通过与 ASP.NET 和 Visual Studio 团队合作开发了一些重大的增强功能,让开发人员能够轻松使用 Win ...

  6. Winbind authentication against active directory

    Winbind authentication against active directory Description This tip will describe how to configure ...

  7. ASP.NET MVC 随想录——探索ASP.NET Identity 身份验证和基于角色的授权,中级篇

    在前一篇文章中,我介绍了ASP.NET Identity 基本API的运用并创建了若干用户账号.那么在本篇文章中,我将继续ASP.NET Identity 之旅,向您展示如何运用ASP.NET Ide ...

  8. ASP.NET MVC 随想录——开始使用ASP.NET Identity,初级篇

    在之前的文章中,我为大家介绍了OWIN和Katana,有了对它们的基本了解后,才能更好的去学习ASP.NET Identity,因为它已经对OWIN 有了良好的集成. 在这篇文章中,我主要关注ASP. ...

  9. ASP.NET MVC 随想录——开始使用ASP.NET Identity,初级篇(转)

    ASP.NET MVC 随想录——开始使用ASP.NET Identity,初级篇   阅读目录 ASP.NET Identity 前世今生 建立 ASP.NET Identity 使用ASP.NET ...

随机推荐

  1. COGS.1822.[AHOI2013]作业(莫队 树状数组/分块)

    题目链接: COGS.BZOJ3236 Upd: 树状数组实现的是单点加 区间求和,采用值域分块可以\(O(1)\)修改\(O(sqrt(n))\)查询.同BZOJ3809. 莫队为\(O(n^{1. ...

  2. BZOJ.3809.Gty的二逼妹子序列(分块 莫队)

    题目链接 /* 25832 kb 26964 ms 莫队+树状数组:增加/删除/查询 都是O(logn)的,总时间复杂度O(m*sqrt(n)*logn),卡不过 莫队+分块:这样查询虽然变成了sqr ...

  3. 107. 二叉树的层次遍历 II

    107. 二叉树的层次遍历 II 题意 给定一个二叉树,返回其节点值自底向上的层次遍历. (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历). 解题思路 递归:利用前序遍历的思想,在递归过程中 ...

  4. Codeforces Round #407 div2 题解【ABCDE】

    Anastasia and pebbles 题意:你有两种框,每个框可以最多装k重量的物品,但是你每个框不能装不一样的物品.现在地面上有n个物品,问你最少多少次,可以把这n个物品全部装回去. 题解:其 ...

  5. Python基础语法-基本数据类型

    此文档解决以下问题: 一.Python中数值数据类型——整型(int).浮点型(float).布尔型(bool).复数(complex) 1.float()函数的运用 2.int()函数的运用 3.t ...

  6. 推荐两款好用的反编译工具(Luyten,Jadx)

    使用JD-Gui打开单个.class文件,总是报错// INTERNAL ERROR 但当我用jd-gui反编译前面操作获得的jar文件的时,但有一部分类不能显示出来--constants类,仅仅显示 ...

  7. PID控制器(比例-积分-微分控制器)- IV

    调节/测量放大电路电路图:PID控制电路图 如图是PlD控制电路,即比例(P).积分(I).微分(D)控制电路. A1构成的比例电路与环路增益有关,调节RP1,可使反相器的增益在0·5一∞范围内变化; ...

  8. SpringBoot(八):系统错误统一拦截器

    在日常 web 开发中发生了异常,往往需要通过一个统一的 异常处理,来保证客户端能够收到友好的提示.本文将会介绍 Spring Boot 中的 全局统一异常处理. Springboot的全局异常查是通 ...

  9. C#语言

    封面 书名 版权 前言 目录 第Ⅰ部分 C#语言 第1章  NET体系结构 1.1  C#与.NET的关系 1.2  公共语言运行库 1.2.1  平台无关性 1.2.2  提高性能 1.2.3  语 ...

  10. CS模式,客户端页面加载

    public MainForm() { //1.初始化视图 InitializeComponent(); //2.加载程序 this.Load += new System.EventHandler(t ...