.net core 5 Windows 身份验证和 Active Directory 资源

mcr*_*ore 5 .net c# asp.net-mvc asp.net-core asp.net-core-5.0

嘿伙计们,只是一个没有代码的直接问题。我什至都在努力寻找简单问题的基本答案。

我究竟如何能够并且应该使用 Windows 身份验证(不是集成的 Windows 身份验证)与 Active Directory 进行身份验证然后授权?您可能认为会有一百万个示例项目,但我的 .net core 搜索结果中 80% 都是旧的 ASP.NET 文章,这些文章已经过时,并且不适用于较新的版本。

我在这里有很多工作示例,但它们都使用 System.Web 类/库,但现在都已弃用,不再对我有用。

我从旧的 ASP.NET 项目中获得的代码和方法看起来都非常简单,否则我很困惑为什么我找不到 .NET Core 的类似内容?在我读到的大多数文章中,一切都是一些小众的第三方软件包,而我只想以普通的微软方式来做,我发现很难相信没有一个简单的解决方案用于登录屏幕和针对 AD 的身份验证。微软文档感觉他们的目标客户是那些得到一点小提示并确切知道该怎么做的专家。

我是一名刚刚工作了 4 个月的研究生,对 .net core 很陌生。

我已经了解了 LDAP、声明、主体、cookie 和更多兔子洞,但只是对所有不同版本的 .net 及其类/库等感到更加困惑。

bmi*_*ler 8

有一个 nuget 可以处理这个问题;系统.目录服务.帐户管理

它仅适用于 Windows,有一个我认为是跨平台的 Novel ldap 版本。

进行身份验证:

using (var ctx = new PrincipalContext(ContextType.Domain))
{
    if (!ctx.ValidateCredentials(user_name, password))
        throw new Exception("unknown username or password");

    using (var userPrincipal = new UserPrincipal(ctx)) {
        userPrincipal.SamAccountName = user_name;

        using (var search = new PrincipalSearcher(userPrincipal))
        {
            UserPrincipal user = (UserPrincipal) search.FindOne();
            if (user == null) {
                throw new Exception("user authenticated but not found in directory");
            }
            return user; // auth'ed user
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

授权(按组成员身份):

using (var ctx = new PrincipalContext(ContextType.Domain))
{
    using (var groupPrincipal = new GroupPrincipal(ctx))
    {
        groupPrincipal.SamAccountName = groupName;
        using (var search = new PrincipalSearcher(groupPrincipal))
        {
            member_list = GetMembersOfPrincipalGroup((GroupPrincipal)search.FindOne());
        }
        // member_list contains all the users of a group. 
        // I cache these in a Dictionary for faster group membership checks
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,ContextType 枚举处理本地计算机用户和域。在 nuget 包上搜索更多示例。