web-dev-qa-db-fra.com

Authentification Active Directory LDAP ASP.NET Core 2.0

J'ai trouvé beaucoup d'informations du passé qui disent que l'authentification LDAP n'est pas encore activée, mais vous pouvez contourner cela en utilisant des packages tiers. Cependant, il semble que l'authentification LDAP était WAS implémentée retour en janvier . Je n'arrive pas à trouver aucune information sur COMMENT l'implémenter.

J'ai déjà authentification personnalisée configurée dans mon projet, il me faut juste la logique pour renseigner la méthode HandleAuthenticateAsync.

J'ai essayé d'utiliser autres exemples , mais ils ne semblent pas fonctionner avec .NET Core 2.0.

Voici le seul code pertinent que j'ai que je peux penser à poster

protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
    // Get Authorization header value
    if (!Request.Headers.TryGetValue(HeaderNames.Authorization, out var authorization)) {
        return Task.FromResult(AuthenticateResult.Fail("Cannot read authorization header."));
    }

    // TODO: Authenticate user

    // Create authenticated user ticket
    var identities = new List<ClaimsIdentity> { new ClaimsIdentity("custom auth type") };
    var ticket = new AuthenticationTicket(new ClaimsPrincipal(identities), Options.Scheme);

    return Task.FromResult(AuthenticateResult.Success(ticket));

    // else User not authenticated
    return Task.FromResult(AuthenticateResult.Fail("Invalid auth key."));
}

Ma question est donc la suivante: comment implémenter l'authentification LDAP dans .NET Core 2.0?

28
Window

Grâce à Win Answer pour m'avoir signalé que je devais utiliser le pack de compatibilité Windows , j'ai pu comprendre cela.

La première chose à faire était d’installer le paquet de Nuget

Install-Package Microsoft.Windows.Compatibility 

À l'époque, j'avais besoin d'une version d'aperçu. J'ai donc ajouté -Version 2.0.0-preview1-26216-02 à la fin de cette commande

Ensuite, ajoutez les instructions using pour System.DirectoryServices et System.DirectoryServices.AccountManagement

Ensuite, branchez cette logique dans ma méthode HandleAuthenticateAsync:

const string LDAP_PATH = "EX://exldap.example.com:5555";
const string LDAP_DOMAIN = "exldap.example.com:5555";

using (var context = new PrincipalContext(ContextType.Domain, LDAP_DOMAIN, "service_acct_user", "service_acct_pswd")) {
    if (context.ValidateCredentials(username, password)) {
        using (var de = new DirectoryEntry(LDAP_PATH))
        using (var ds = new DirectorySearcher(de)) {
            // other logic to verify user has correct permissions

            // User authenticated and authorized
            var identities = new List<ClaimsIdentity> { new ClaimsIdentity("custom auth type") };
            var ticket = new AuthenticationTicket(new ClaimsPrincipal(identities), Options.Scheme);
            return Task.FromResult(AuthenticateResult.Success(ticket));
        }
    }
}

// User not authenticated
return Task.FromResult(AuthenticateResult.Fail("Invalid auth key."));
26
Window

Selon # 2089 , il est uniquement disponible dans le pack de compatibilité Windows pour .NET Core. J'utilise actuellement 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;
}

Pour l'authentification et l'autorisation, nous pouvons utiliser Middleware d'authentification par cookie avec des revendications.

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
   });
}

Il a peu de pièces en mouvement, j'ai donc créé un exemple de projet sur GitHub. Il existe deux pièces principales - LdapAuthenticationService et SignInManager .

22
Win