Интеграционная котельная плита Ldap - PullRequest
0 голосов
/ 14 июня 2019

Я буду использовать аутентификацию Ldap для проекта Asp.Net BoilerPlate.Я создал классы из документации: AuthenticationSource.cs, LdapSettingProvider.cs, LdapSettings.cs, CoreModule, LdapConsts.cs.Я хочу прочитать информацию Ldap из appsettings.json, а затем пройти аутентификацию из Ldap.Что я должен сделать для использования Ldap?

public class LdapSettingProvider : SettingProvider
{
    public override IEnumerable<SettingDefinition> GetSettingDefinitions(SettingDefinitionProviderContext context)
    {
        var result = new[]
               {
                   new SettingDefinition(LdapSettingNames.IsEnabled, "true", L("Ldap_IsEnabled"), scopes: SettingScopes.Application | SettingScopes.Tenant, isInherited: false),
                   new SettingDefinition(LdapSettingNames.ContextType, ContextType.Domain.ToString(), L("Ldap_ContextType"), scopes: SettingScopes.Application | SettingScopes.Tenant, isInherited: false),
                   new SettingDefinition(LdapSettingNames.Container, null, L("Ldap_Container"), scopes: SettingScopes.Application | SettingScopes.Tenant, isInherited: false),
                   new SettingDefinition(LdapSettingNames.Domain, null, L("LDAP://10.222.8.20"), scopes: SettingScopes.Application | SettingScopes.Tenant, isInherited: false),
                   new SettingDefinition(LdapSettingNames.UserName, null, L("Ldap_UserName"), scopes: SettingScopes.Application | SettingScopes.Tenant, isInherited: false),
                   new SettingDefinition(LdapSettingNames.Password, null, L("Ldap_Password"), scopes: SettingScopes.Application | SettingScopes.Tenant, isInherited: false)
               };
        return result;
    }

    private static ILocalizableString L(string name)
    {
        var result =  new LocalizableString(name, PkdsLdapConsts.LocalizationLdapSourceName);
        return result;
    }
}
public class PkdsCoreModule : AbpModule
{
    public override void PreInitialize()
    {
        Configuration.Auditing.IsEnabledForAnonymousUsers = true;

        // Declare entity types
        Configuration.Modules.Zero().EntityTypes.Tenant = typeof(Tenant);
        Configuration.Modules.Zero().EntityTypes.Role = typeof(Role);
        Configuration.Modules.Zero().EntityTypes.User = typeof(User);
        PkdsLocalizationConfigurer.Configure(Configuration.Localization);

        //LDAP buraya eklenecek. Configure buraya eklenecek.
        PkdsLdapLocalizationConfigurer.Configure(Configuration.Localization);
        Configuration.Settings.Providers.Add<Authentication.LdapSettingProvider>();
        IocManager.Register<ILdapSettings, PkdsLdapSettings>();
        Configuration.Modules.ZeroLdap().Enable(typeof(LdapAuthenticationSource));

        // Enable this line to create a multi-tenant application.
        Configuration.MultiTenancy.IsEnabled = PkdsConsts.MultiTenancyEnabled;

        // Configure roles
        AppRoleConfig.Configure(Configuration.Modules.Zero().RoleManagement);

        Configuration.Settings.Providers.Add<AppSettingProvider>();

        Configuration.UnitOfWork.OverrideFilter(AbpDataFilters.MayHaveTenant, false);
        Configuration.UnitOfWork.OverrideFilter(AbpDataFilters.MustHaveTenant, false);
    }

    public override void Initialize()
    {
        IocManager.RegisterAssemblyByConvention(typeof(PkdsCoreModule).GetAssembly());
    }

    public override void PostInitialize()
    {
        IocManager.Resolve<AppTimes>().StartupTime = Clock.Now;
    }
}
public class PkdsLdapConsts
{
    public const string LocalizationLdapSourceName = "Ldap";

    public const string ConnectionStringName = "Default";

    public const bool MultiTenancyEnabled = false;
}
public class PkdsLdapSettings : ILdapSettings
{
    protected ISettingManager SettingManager { get; }

    public PkdsLdapSettings(ISettingManager settingManager)
    {
        SettingManager = settingManager;
    }

    public virtual Task<bool> GetIsEnabled(int? tenantId)
    {
        var result = tenantId.HasValue
            ? SettingManager.GetSettingValueForTenantAsync<bool>(LdapSettingNames.IsEnabled, tenantId.Value)
            : SettingManager.GetSettingValueForApplicationAsync<bool>(LdapSettingNames.IsEnabled);

        return result;
    }

    public virtual async Task<ContextType> GetContextType(int? tenantId)
    {
        var result = tenantId.HasValue
            ? (await SettingManager.GetSettingValueForTenantAsync(LdapSettingNames.ContextType, tenantId.Value)).ToEnum<ContextType>()
            : (await SettingManager.GetSettingValueForApplicationAsync(LdapSettingNames.ContextType)).ToEnum<ContextType>();
        return result;
    }

    public virtual Task<string> GetContainer(int? tenantId)
    {
        var result = tenantId.HasValue
            ? SettingManager.GetSettingValueForTenantAsync(LdapSettingNames.Container, tenantId.Value)
            : SettingManager.GetSettingValueForApplicationAsync(LdapSettingNames.Container);
        return result;
    }

    public virtual Task<string> GetDomain(int? tenantId)
    {
        var result = tenantId.HasValue
            ? SettingManager.GetSettingValueForTenantAsync(LdapSettingNames.Domain, tenantId.Value)
            : SettingManager.GetSettingValueForApplicationAsync(LdapSettingNames.Domain);

        return result;
    }

    public virtual Task<string> GetUserName(int? tenantId)
    {
        var result = tenantId.HasValue
            ? SettingManager.GetSettingValueForTenantAsync(LdapSettingNames.UserName, tenantId.Value)
            : SettingManager.GetSettingValueForApplicationAsync(LdapSettingNames.UserName);
        return result;
    }

    public virtual Task<string> GetPassword(int? tenantId)
    {
        var result = tenantId.HasValue
            ? SettingManager.GetSettingValueForTenantAsync(LdapSettingNames.Password, tenantId.Value)
            : SettingManager.GetSettingValueForApplicationAsync(LdapSettingNames.Password);
        return result;
    }
}
public class LdapSettingProvider : SettingProvider
{
    public override IEnumerable<SettingDefinition> GetSettingDefinitions(SettingDefinitionProviderContext context)
    {
        var result = new[]
               {
                   new SettingDefinition(LdapSettingNames.IsEnabled, "true", L("Ldap_IsEnabled"), scopes: SettingScopes.Application | SettingScopes.Tenant, isInherited: false),
                   new SettingDefinition(LdapSettingNames.ContextType, ContextType.Domain.ToString(), L("Ldap_ContextType"), scopes: SettingScopes.Application | SettingScopes.Tenant, isInherited: false),
                   new SettingDefinition(LdapSettingNames.Container, null, L("Ldap_Container"), scopes: SettingScopes.Application | SettingScopes.Tenant, isInherited: false),
                   new SettingDefinition(LdapSettingNames.Domain, null, L("LDAP://10.222.8.20"), scopes: SettingScopes.Application | SettingScopes.Tenant, isInherited: false),
                   new SettingDefinition(LdapSettingNames.UserName, null, L("Ldap_UserName"), scopes: SettingScopes.Application | SettingScopes.Tenant, isInherited: false),
                   new SettingDefinition(LdapSettingNames.Password, null, L("Ldap_Password"), scopes: SettingScopes.Application | SettingScopes.Tenant, isInherited: false)
               };
        return result;
    }

    private static ILocalizableString L(string name)
    {
        var result =  new LocalizableString(name, PkdsLdapConsts.LocalizationLdapSourceName);
        return result;
    }
}
public class LdapAuthenticationSource : LdapAuthenticationSource<Tenant, User>
{
    public LdapAuthenticationSource(ILdapSettings settings, IAbpZeroLdapModuleConfig ldapModuleConfig)
        : base(settings, ldapModuleConfig)
    {
    }
    public override Task<bool> TryAuthenticateAsync(string userNameOrEmailAddress, string plainPassword, Tenant tenant)
    {
        return base.TryAuthenticateAsync(userNameOrEmailAddress, plainPassword, tenant);
    }
}

Что я должен определить в LdapSettingProvider, а затем другие шаги?

1 Ответ

0 голосов
/ 17 июня 2019

После того как вы настроили пользовательскую внешнюю аутентификацию, abp автоматически обработает ее в AbpLoginManager#LoginAsync()

Если вы хотите войти с внешней аутентификацией через API, см. TokenAuthController # ExternalAuthenticate ()

В противном случае для внешней аутентификации MVC см. AccountController # Login ()

Относительно того, как ABP обрабатывает аутентификацию LDAP, LdapAuthenticationSource # CreatePrincipalContext подключается к домену LDAP, как настроено в настройках (см. LdapSettingNames), с использованием PrincipalContext.

Эта аутентификация выполняется во время AbpLoginManager#LoginAsync(), проходя через все внешние типы аутентификации, которые включены через

Configuration.Modules.ZeroLdap().Enable(typeof(LdapAuthenticationSource));
...