使用用户凭据和角色的Active Directory身份验证

时间:2017-01-09 08:47:44

标签: asp.net c#-4.0

是Active Directory身份验证和asp.net的新手。我想用以下过滤器实现活动目录身份验证: 一个。用户将使用他的系统凭据登录。 湾如果应报告密码/名称不匹配,则需要使用AD验证用户名和密码。 C。需要从服务器获取用户角色,以便我可以在我的应用程序中实现页面访问权限。 d。我想验证3种类型的用户1.管理员,2。非管理员和3.未注册用户。因此,基于角色,我可以配置页面访问权限。

1 个答案:

答案 0 :(得分:0)

我找到了简单的解决方案,可以轻松地用于具有用户角色的AD身份验证。为此我们基本上需要遵循以下输入: 1. LDAPServerAddress 2.组名:admin,users或其他组。 获取上述信息后,创建了一个包含以下代码的公共库项目并导入到您的项目中。 第1步:在VS中创建库项目。 step2:创建AD对象类,如下所示:

public class ActiveDirectoryInfo
    {
        public string UserName { get; set; }
        public bool IsAuthentic { get; set; }
        public string UserDisplayName { get; set; }
        public string Password { get; set; }
        public string LdapServerName { get; set; }
        public string AdminGroupName { get; set; }
        public string UserGroupName { get; set; }
        public enum Role { Administrator, User, ReadOnly };
        public Role Authorization { get; set; }
    }

步骤3:使用上面的对象和值使用以下代码检查AD:

 public class ActiveDirectoryHelper
{
    /// <summary>
    /// Private variable for Principal Context
    /// </summary>
    private PrincipalContext context = null;

    /// <summary>
    /// Public property for Principal Context
    /// </summary>
    public PrincipalContext Context
    {
        get { return context; }
        set { context = value; }
    }

    public ActiveDirectoryInfo adInfo = null;
    /// <summary>
    /// Constructor 
    /// </summary>
    public ActiveDirectoryHelper(ActiveDirectoryInfo adInfo)
    {
        context = new PrincipalContext(ContextType.Domain, adInfo.LdapServerName + ":636", null, ContextOptions.SecureSocketLayer | ContextOptions.Negotiate); //'636 is the port used Secure connection'
    }

    /// <summary>
    /// To Check if the user is Authentic in Active Directory
    /// </summary>
    /// <param name="userName">UserName</param>
    /// <param name="password">Password</param>
    /// <returns>IsAuthentic</returns>
    public bool IsAuthenticUser(ActiveDirectoryInfo adInfo)
    {

        try
        {
            adInfo.IsAuthentic = context.ValidateCredentials(adInfo.UserName, adInfo.Password, ContextOptions.ServerBind);
        }

        catch (ArgumentException aex)
        {
            LogInfo.LogNLogUnhandledError("Invalid User Name or Password", aex);
        }
        catch (Exception ex)
        {
            LogInfo.LogNLogUnhandledError("Could not authenticate User", ex);
        }
        return adInfo.IsAuthentic;
    }

    /// <summary>
    /// To get the Display UserName from Active Directory
    /// </summary>
    /// <param name="userName">UserName</param>       
    /// <returns>UserDisplayName</returns>
    public string AuthenticUserName(ActiveDirectoryInfo adInfo)
    {
        try
        {
            UserPrincipal user = new UserPrincipal(context);
            user.SamAccountName = adInfo.UserName;
            // perform the search 
            PrincipalSearcher search = new PrincipalSearcher(user);
            user = (UserPrincipal)search.FindOne();
            search.Dispose();
            adInfo.UserDisplayName = user.DisplayName;
        }

        catch (ArgumentException aex)
        {
            LogInfo.LogNLogUnhandledError("Invalid User Name ", aex.InnerException);
        }

        catch (Exception ex)
        {
            LogInfo.LogNLogUnhandledError("Error in AuthenticateUserName ", ex.InnerException);
        }

        return adInfo.UserDisplayName;
    }

    /// <summary>
    /// To Check if the User belongs to a Authorized group in Active Directory
    /// </summary>
    /// <param name="userName">UserName</param>
    /// <param name="password">Password</param>
    /// <returns>UserRole</returns>
    public ActiveDirectoryInfo.Role AuthorizedGroup(ActiveDirectoryInfo adInfo)
    {

        try
        {
            GroupPrincipal adminGroup = GroupPrincipal.FindByIdentity(context, IdentityType.Name, adInfo.AdminGroupName);
            GroupPrincipal userGroup = GroupPrincipal.FindByIdentity(context, IdentityType.Name, adInfo.UserGroupName);
            UserPrincipal user = new UserPrincipal(context);
            user.SamAccountName = adInfo.UserName;
            PrincipalSearcher search = new PrincipalSearcher(user);
            user = (UserPrincipal)search.FindOne();
            PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();

            // check if user is member of that group
            if (groups.Contains(adminGroup))
            {
                adInfo.Authorization = ActiveDirectoryInfo.Role.Administrator;
            }
            else if (groups.Contains(userGroup))
            {
                adInfo.Authorization = ActiveDirectoryInfo.Role.User;
            }
            else
            {
                adInfo.Authorization = ActiveDirectoryInfo.Role.ReadOnly;
            }
        }

        catch (System.ComponentModel.InvalidEnumArgumentException ienumarex)
        {
            LogInfo.LogNLogUnhandledError("Invalid Group Name", ienumarex.InnerException);
        }
        catch (ArgumentException aex)
        {
            LogInfo.LogNLogUnhandledError("Invalid User Name or Password", aex.InnerException);
        }

        catch (Exception ex)
        {
            LogInfo.LogNLogUnhandledError("User Cannot be Authorised", ex.InnerException);
        }

        return adInfo.Authorization;
    }
}