gpt4 book ai didi

c# - 身份 - 自定义用户验证器

转载 作者:行者123 更新时间:2023-11-30 19:53:43 29 4
gpt4 key购买 nike

您好,

我有一个带有 Identity 的 .NetCore MVC APP并使用 this指导我能够创建自定义用户验证器。

public class UserDomainValidator<TUser> : IUserValidator<TUser> 
where TUser : IdentityUser
{
private readonly List<string> _allowedDomains = new List<string>
{
"elanderson.net",
"test.com"
};

public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager,
TUser user)
{
if (_allowedDomains.Any(allowed =>
user.Email.EndsWith(allowed, StringComparison.CurrentCultureIgnoreCase)))
{
return Task.FromResult(IdentityResult.Success);
}

return Task.FromResult(
IdentityResult.Failed(new IdentityError
{
Code = "InvalidDomain",
Description = "Domain is invalid."
}));
}
}

并通过将其添加到 DI 中的身份服务来成功验证我的用户创建

services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.User.AllowedUserNameCharacters = "abccom.";
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddUserValidator<UserDomainValidator<ApplicationUser>>();

现在,one of the existing validatiors在 Identity 中声明用户名必须是唯一的

private async Task ValidateUserName(UserManager<TUser> manager, TUser user, ICollection<IdentityError> errors)
{
var userName = await manager.GetUserNameAsync(user);
if (string.IsNullOrWhiteSpace(userName))
{
errors.Add(Describer.InvalidUserName(userName));
}
else if (!string.IsNullOrEmpty(manager.Options.User.AllowedUserNameCharacters) &&
userName.Any(c => !manager.Options.User.AllowedUserNameCharacters.Contains(c)))
{
errors.Add(Describer.InvalidUserName(userName));
}
else
{
var owner = await manager.FindByNameAsync(userName);
if (owner != null &&
!string.Equals(await manager.GetUserIdAsync(owner), await manager.GetUserIdAsync(user)))
{
errors.Add(Describer.DuplicateUserName(userName));
}
}
}

因为在我的应用程序中我的登录是通过租户 + 用户名/租户 + 电子邮件完成的,我想允许重复的用户名...有没有人做过类似的事情或有任何想法?

我需要删除此验证,我想调整 SignInManager 或其他东西,以便它可以登录正确的用户..

最佳答案

不是添加新的验证器,而是替换服务中添加的验证器,而是创建您自己的 UserValidator。

   services.Replace(ServiceDescriptor.Scoped<IUserValidator<User>, CustomUserValidator<User>>());


public class CustomUserValidator<TUser> : IUserValidator<TUser> where TUser : class
{

private readonly List<string> _allowedDomains = new List<string>
{
"elanderson.net",
"test.com"
};

public CustomUserValidator(IdentityErrorDescriber errors = null)
{
Describer = errors ?? new IdentityErrorDescriber();
}

public IdentityErrorDescriber Describer { get; }


public virtual async Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user)
{
if (manager == null)
throw new ArgumentNullException(nameof(manager));
if (user == null)
throw new ArgumentNullException(nameof(user));
var errors = new List<IdentityError>();
await ValidateUserName(manager, user, errors);
if (manager.Options.User.RequireUniqueEmail)
await ValidateEmail(manager, user, errors);
return errors.Count > 0 ? IdentityResult.Failed(errors.ToArray()) : IdentityResult.Success;
}

private async Task ValidateUserName(UserManager<TUser> manager, TUser user, ICollection<IdentityError> errors)
{
var userName = await manager.GetUserNameAsync(user);
if (string.IsNullOrWhiteSpace(userName))
errors.Add(Describer.InvalidUserName(userName));
else if (!string.IsNullOrEmpty(manager.Options.User.AllowedUserNameCharacters) && userName.Any(c => !manager.Options.User.AllowedUserNameCharacters.Contains(c)))
{
errors.Add(Describer.InvalidUserName(userName));
}
}

private async Task ValidateEmail(UserManager<TUser> manager, TUser user, List<IdentityError> errors)
{
var email = await manager.GetEmailAsync(user);
if (string.IsNullOrWhiteSpace(email))
errors.Add(Describer.InvalidEmail(email));
else if (!new EmailAddressAttribute().IsValid(email))
{
errors.Add(Describer.InvalidEmail(email));
}
else if (_allowedDomains.Any(allowed =>
email.EndsWith(allowed, StringComparison.CurrentCultureIgnoreCase)))
{
errors.Add(new IdentityError
{
Code = "InvalidDomain",
Description = "Domain is invalid."
});
}
else
{
var byEmailAsync = await manager.FindByEmailAsync(email);
var flag = byEmailAsync != null;
if (flag)
{
var a = await manager.GetUserIdAsync(byEmailAsync);
flag = !string.Equals(a, await manager.GetUserIdAsync(user));
}
if (!flag)
return;
errors.Add(Describer.DuplicateEmail(email));
}
}
}

关于c# - 身份 - 自定义用户验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46911327/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com