首页 文章

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

提问于
浏览
0

有必要使系统能够使用本地帐户(如框中的常规标识)授权用户,并使用Active Directory帐户(通过LDAP提供程序) . 如何在ASP.Net Core项目中完成,如何在系统中注册这样的授权方法(意思是启动类)?在以前的版本中,据我所知,它可以使用FormAuthentication解决,但在登录之前,请检查其中一个提供程序中的用户(您可以强制用户提前指定其帐户的类型) . 我不知道如何在ASP.Net Core中这样做,我没有在网络上找到类似的例子 .

1 回答

  • 1

    到目前为止,System.DirectoryServices在ASP.NET Core中不可用 . 你可以阅读更多here . 但是,我们可以使用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创建了一个working sample project .

相关问题