Helloes,
I have a .NetCore MVC APP with Identity and using this guide I was able to create custom user validators.
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."
}));
}
}
and succesfully validate my User creation by adding it to my Identity service in DI
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.User.AllowedUserNameCharacters = "abccom.";
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddUserValidator<UserDomainValidator<ApplicationUser>>();
Now, one of the existing validatiors in Identity states that the username must be unique
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));
}
}
}
Since in my app my login is done via Tenant + Username / Tenant + Email, I want to allow duplicated usernames... has anyone done something similar or have any ideas?
I need to remove this validation and I guess to adapt the SignInManager or something so it can sign in the correct user..