Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP样板文件中LDAP实现上的InvalidCastException_C#_Asp.net_Asp.net Boilerplate - Fatal编程技术网

C# ASP样板文件中LDAP实现上的InvalidCastException

C# ASP样板文件中LDAP实现上的InvalidCastException,c#,asp.net,asp.net-boilerplate,C#,Asp.net,Asp.net Boilerplate,大家好,最近我们不得不为我们的应用程序实现一个Active Directory,在过去几天尝试登录该站点时,我们遇到了一个InvalidCastException。我一直在绞尽脑汁试图找出导致此错误的原因。代码似乎运行良好,因为加载时没有错误 ldapaauthentication.cs: public abstract class LdapAuthenticationSource<TTenant, TUser> : DefaultExternalAuthenticationSou

大家好,最近我们不得不为我们的应用程序实现一个Active Directory,在过去几天尝试登录该站点时,我们遇到了一个InvalidCastException。我一直在绞尽脑汁试图找出导致此错误的原因。代码似乎运行良好,因为加载时没有错误

ldapaauthentication.cs:

 public abstract class LdapAuthenticationSource<TTenant, TUser> : DefaultExternalAuthenticationSource<TTenant, TUser>, ITransientDependency
        where TTenant : AbpTenant<TUser>
        where TUser : AbpUserBase, new()
    {

        /// <summary>
        /// LDAP
        /// </summary>
        public const string SourceName = "LDAP";

        public override string Name
        {
            get { return SourceName; }
        }

        private readonly ILdapSettings _settings;
        private readonly IAbpZeroLdapModuleConfig _ldapModuleConfig;

        protected LdapAuthenticationSource(ILdapSettings settings, IAbpZeroLdapModuleConfig ldapModuleConfig)
        {
            _settings = settings;
            _ldapModuleConfig = ldapModuleConfig;
        }

        /// <inheritdoc/>
        public override async Task<bool> TryAuthenticateAsync(string userNameOrEmailAddress, string plainPassword, TTenant tenant)
        {
            if (!_ldapModuleConfig.IsEnabled || !(await _settings.GetIsEnabled(GetIdOrNull(tenant))))
            {
                return false;
            }

            using (var principalContext = await CreatePrincipalContext(tenant))
            {
                return ValidateCredentials(principalContext, userNameOrEmailAddress, plainPassword);
            }
        }

        /// <inheritdoc/>
        public async override Task<TUser> CreateUserAsync(string userNameOrEmailAddress, TTenant tenant)
        {
            await CheckIsEnabled(tenant);

            var user = await base.CreateUserAsync(userNameOrEmailAddress, tenant);

            using (var principalContext = await CreatePrincipalContext(tenant))
            {
                var userPrincipal = UserPrincipal.FindByIdentity(principalContext, userNameOrEmailAddress);

                if (userPrincipal == null)
                {
                    throw new AbpException("Unknown LDAP user: " + userNameOrEmailAddress);
                }

                UpdateUserFromPrincipal(user, userPrincipal);

                user.IsEmailConfirmed = true;
                user.IsActive = true;

                return user;
            }
        }

        public async override Task UpdateUserAsync(TUser user, TTenant tenant)
        {
            await CheckIsEnabled(tenant);

            await base.UpdateUserAsync(user, tenant);

            using (var principalContext = await CreatePrincipalContext(tenant))
            {
                var userPrincipal = UserPrincipal.FindByIdentity(principalContext, user.UserName);

                if (userPrincipal == null)
                {
                    throw new AbpException("Unknown LDAP user: " + user.UserName);
                }

                UpdateUserFromPrincipal(user, userPrincipal);
            }
        }

        protected virtual bool ValidateCredentials(PrincipalContext principalContext, string userNameOrEmailAddress, string plainPassword)
        {
            return principalContext.ValidateCredentials(userNameOrEmailAddress, plainPassword, ContextOptions.Negotiate);
        }

        protected virtual void UpdateUserFromPrincipal(TUser user, UserPrincipal userPrincipal)
        {
            user.UserName = userPrincipal.SamAccountName;
            user.Name = userPrincipal.GivenName;
            user.Surname = userPrincipal.Surname;
            user.EmailAddress = userPrincipal.EmailAddress;

            if (userPrincipal.Enabled.HasValue)
            {
                user.IsActive = userPrincipal.Enabled.Value;
            }
        }

        protected virtual async Task<PrincipalContext> CreatePrincipalContext(TTenant tenant)
        {
            var tenantId = GetIdOrNull(tenant);

            return new PrincipalContext(
                await _settings.GetContextType(tenantId),
                ConvertToNullIfEmpty(await _settings.GetDomain(tenantId)),
                ConvertToNullIfEmpty(await _settings.GetContainer(tenantId)),
                ConvertToNullIfEmpty(await _settings.GetUserName(tenantId)),
                ConvertToNullIfEmpty(await _settings.GetPassword(tenantId))
                );
        }

        private async Task CheckIsEnabled(TTenant tenant)
        {
            if (!_ldapModuleConfig.IsEnabled)
            {
                throw new AbpException("Ldap Authentication module is disabled globally!");
            }

            var tenantId = GetIdOrNull(tenant);
            if (!await _settings.GetIsEnabled(tenantId))
            {
                throw new AbpException("Ldap Authentication is disabled for given tenant (id:" + tenantId + ")! You can enable it by setting '" + LdapSettingNames.IsEnabled + "' to true");
            }
        }

        private static int? GetIdOrNull(TTenant tenant)
        {
            return tenant == null
                ? (int?)null
                : tenant.Id;
        }

        private static string ConvertToNullIfEmpty(string str)
        {
            return str.IsNullOrWhiteSpace()
                ? null
                : str;
        }

    }
}
公共抽象类LdapAuthenticationSource:DefaultExternalAuthenticationSource,ITransientDependency
其中TTenant:AbpTenant
其中TUser:AbpUserBase,new()
{
/// 
///LDAP
/// 
public const string SourceName=“LDAP”;
公共重写字符串名
{
获取{return SourceName;}
}
私有只读ILdapSettings\u设置;
专用只读IAbpZeroLdapModuleConfig _ldapModuleConfig;
受保护的LdapAuthenticationSource(ILdapSettings设置,IAbpZeroLdapModuleConfig ldapModuleConfig)
{
_设置=设置;
_ldapModuleConfig=ldapModuleConfig;
}
/// 
公共覆盖异步任务TryAuthenticateAncy(字符串用户名或邮箱地址、字符串明文密码、TTenant租户)
{
如果(!\u ldapModuleConfig.IsEnabled | |!(等待设置.GetIsEnabled(GetIdOrNull(租户)))
{
返回false;
}
使用(var principalContext=await CreatePrincipalContext(租户))
{
返回ValidateCredentials(principalContext、用户名或邮箱地址、普通密码);
}
}
/// 
公共异步覆盖任务CreateUserAsync(字符串userNameOrEmailAddress,TTenant租户)
{
等待检查已启用(租户);
var user=await base.CreateUserAsync(userNameOrEmailAddress,租户);
使用(var principalContext=await CreatePrincipalContext(租户))
{
var userPrincipal=userPrincipal.FindByIdentity(principalContext,userNameOrEmailAddress);
if(userPrincipal==null)
{
抛出新的AbpException(“未知LDAP用户:+userNameOrEmailAddress”);
}
UpdateUserFromPrincipal(用户,用户主体);
user.isemailcomfixed=true;
user.IsActive=true;
返回用户;
}
}
公共异步覆盖任务UpdateUserAsync(TUser用户,TTenant租户)
{
等待检查已启用(租户);
wait base.UpdateUserAsync(用户、租户);
使用(var principalContext=await CreatePrincipalContext(租户))
{
var userPrincipal=userPrincipal.FindByIdentity(principalContext,user.UserName);
if(userPrincipal==null)
{
抛出新的AbpException(“未知LDAP用户:+user.UserName”);
}
UpdateUserFromPrincipal(用户,用户主体);
}
}
受保护的虚拟bool ValidateCredentials(PrincipalContext PrincipalContext,字符串UserName或MailAddress,字符串plainPassword)
{
返回principalContext.ValidateCredentials(用户名或邮箱地址、普通密码、ContextOptions.Negotiate);
}
受保护的虚拟void UpdateUserFromPrincipal(TUser用户、UserPrincipal用户Principal)
{
user.UserName=userPrincipal.SamAccountName;
user.Name=userPrincipal.GivenName;
user.name=userPrincipal.name;
user.EmailAddress=userPrincipal.EmailAddress;
if(userPrincipal.Enabled.HasValue)
{
user.IsActive=userPrincipal.Enabled.Value;
}
}
受保护的虚拟异步任务CreatePrincipalContext(租户)
{
var tenantId=GetIdOrNull(租户);
返回新的PrincipalContext(
等待设置。GetContextType(tenantId),
ConvertToNullIfEmpty(wait_settings.GetDomain(tenantId)),
ConvertToNullIfEmpty(wait_settings.GetContainer(tenantId)),
ConvertToNullIfEmpty(等待设置.GetUserName(租户)),
ConvertToNullIfEmpty(等待设置.GetPassword(tenantId))
);
}
已选中专用异步任务(T租户)
{
如果(!\u ldapModuleConfig.IsEnabled)
{
抛出新的AbpException(“全局禁用Ldap身份验证模块!”);
}
var tenantId=GetIdOrNull(租户);
如果(!wait_settings.GetIsEnabled(tenantId))
{
抛出新的AbpException(“对给定租户(id:“+tenantId+”)禁用Ldap身份验证!您可以通过将“+LdapSettingNames.IsEnabled+””设置为true来启用它”);
}
}
私有静态int?GetIdOrNull(租户)
{
返回租户==null
?(int?)空
:租户身份证;
}
私有静态字符串ConvertToNullIfEmpty(字符串str)
{
return str.IsNullOrWhiteSpace()
无效的
:str;
}
}
}
LdapSettings.cs

public class LdapSettings: ILdapSettings, ITransientDependency
    {

        protected ISettingManager SettingManager { get; }

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

        public virtual Task<bool> GetIsEnabled(int? tenantId)
        {
            return tenantId.HasValue
                ? SettingManager.GetSettingValueForTenantAsync<bool>(AppSettingNames.IsEnabled, tenantId.Value)
                : SettingManager.GetSettingValueForApplicationAsync<bool>(AppSettingNames.IsEnabled);
        }

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

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

        public virtual Task<string> GetDomain(int? tenantId)
        {
            return tenantId.HasValue
                ? SettingManager.GetSettingValueForTenantAsync(AppSettingNames.Domain, tenantId.Value)
                : SettingManager.GetSettingValueForApplicationAsync(AppSettingNames.Domain);
        }

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

        public virtual Task<string> GetPassword(int? tenantId)
        {
            return tenantId.HasValue
                ? SettingManager.GetSettingValueForTenantAsync(AppSettingNames.Password, tenantId.Value)
                : SettingManager.GetSettingValueForApplicationAsync(AppSettingNames.Password);
        }
    }
}
公共类LdapSettings:ILdapSettings、ITransientDependency
{
受保护的ISettingManager设置管理器{get;}
公共LdapSettings(ISettingManager设置管理器)
{
SettingManager=SettingManager;
}
公共虚拟任务GetIsEnabled(int?tenantId)
{
返回tenantId.HasValue
?SettingManager.GetSettingValueForTenantAsync(AppSettingNames.IsEnabled,tenantId.Value)
:SettingManager.GetSettingValueForApplicationAsync(AppSettingNames.IsEnabled);
}
公共虚拟异步任务GetContextT
    [DependsOn(typeof(AbpZeroLdapModule))]
    public class TestApp2020CoreModule : 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);

            TestApp2020LocalizationConfigurer.Configure(Configuration.Localization);

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

            // IocManager.Register<ILdapSettings, MyLdapSettings>(); //change default setting source
            IocManager.Register<ILdapSettings, LdapSettings>();
            Configuration.Modules.ZeroLdap().Enable(typeof(LdapSettings));
            // Configure roles
            AppRoleConfig.Configure(Configuration.Modules.Zero().RoleManagement);

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

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

        public override void PostInitialize()
        {
            IocManager.Resolve<AppTimes>().StartupTime = Clock.Now;
            SettingManager settingsManager = IocManager.Resolve<SettingManager>();
            settingsManager.ChangeSettingForApplication(AppSettingNames.IsEnabled, "true");
        }
    }
}
Configuration.Modules.ZeroLdap().Enable(typeof(LdapSettings));
IocManager.Register<ILdapSettings, LdapSettings>();
Configuration.Modules.ZeroLdap().Enable(typeof(LdapSettings));