ASP.Net 本地用户的核心授权 + LDAP



有必要让系统能够授权用户使用本地帐户(如盒子中的常规身份(和使用Active Directory帐户(通过LDAP提供商任意(。如何在 ASP.Net Core 项目中完成此操作,以及如何在系统(即 Startup 类(中注册这样的授权方法?在以前的版本中,据我所知,可以使用FormAuthentication解决,但是在登录之前,请在其中一个提供程序中检查用户(您可以强制用户提前指定其帐户的类型(。我不知道如何在 ASP.Net Core中执行此操作,并且在网络上也没有找到类似的例子。

System.DirectoryServices目前尚未在 ASP.NET Core中可用。您可以在此处阅读更多内容。但是,我们可以使用Novell.Directory.Ldap.NETStandard。

public bool ValidateUser(string domainName, string username, string password)
{
string userDn = $"{username}@{domainName}";
try
{
using (var connection = new LdapConnection {SecureSocketLayer = false})
{
connection.Connect(domainName, LdapConnection.DEFAULT_PORT);
connection.Bind(userDn, password);
if (connection.Bound)
return true;
}
}
catch (LdapException ex)
{
// Log exception
}
return false;
}

对于身份验证和授权,我们可以将Cookie 身份验证中间件与声明一起使用。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
ILoggerFactory loggerFactory)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{                
AuthenticationScheme = "AuthenticationScheme",
LoginPath = new PathString("/Account/Login"),
AccessDeniedPath = new PathString("/Common/AccessDenied"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
}

它几乎没有活动部分,所以我在 GitHub 上创建了一个工作示例项目。

最新更新