Summary
The Account/Identity modules let one mailbox register several accounts, even with RequireUniqueEmail enabled. The unique-email check runs on NormalizedEmail, and the default ILookupNormalizer only upper-cases the address. Addresses that are different strings but go to the same mailbox are therefore treated as different users.
Environment
Observed on an ABP Commercial application:
- Angular UI, separated auth server, LeptonX theme
- Built-in
Volo.Abp.Account.Public.WebRegister page (RegisterModel), no custom registration code Abp.Account.IsSelfRegistrationEnabled = trueAbp.Identity.SignIn.RequireEmailVerificationToRegister = trueAbp.Account.Captcha.UseCaptchaOnRegistration = false
Email verification does not prevent this: each alias's verification mail lands in the same inbox and is confirmed there. Captcha would only slow down automated sign-ups. It would not stop one person from opening several accounts by hand.
Examples (all delivered to the same inbox)
- Plus addressing / subaddressing (RFC 5233):
name+anything@domain.comgoes toname@domain.com. Gmail, Outlook/Hotmail, iCloud, Proton, Fastmail and most corporate mail servers support it. - Gmail ignores dots in the local part:
first.last@gmail.com=firstlast@gmail.com(also ongooglemail.com).
Impact
- One person can create an unlimited number of accounts with a single mailbox (multi-accounting).
- Any per-account limit (free trial, quota, credits) can easily be bypassed.
- User and sign-up statistics are inflated.
Steps to reproduce
- On an ABP application with self-registration and email verification enabled, register with
firstlast@gmail.comand verify it. - Register with
first.last@gmail.com. The verification mail arrives in the same inbox. After verification, a second, separate account exists. - Register with
firstlast+test@gmail.com. This also creates a separate account.
Request
Please add email canonicalization to the unique-email check in the Account/Identity modules, as a built-in option that applications can turn on or off (for example IdentityOptions.User.CanonicalizeEmail or an Account setting). The canonical form should be built as follows:
- Trim and lower-case the whole address.
- Remove
+and everything after it in the local part, for all domains. - For
gmail.com/googlemail.comonly, remove dots from the local part and treatgooglemail.comasgmail.com. Dots are significant on other domains, so this rule must not apply to them.
The address the user typed must still be stored and used for sending mail. Only the uniqueness check uses the canonical form. Login by email, email login links, email confirmation and password reset must keep working with the address the user registered.
5 Answer(s)
-
0
Hi,
There's no built-in option for this right now. We'll pass it on to the team as a feature request.
You can add it in your own solution today. Store a canonical form of the email in an extra column, and check it in a custom
IUserValidator. Email,NormalizedEmail, login, confirmation and password reset keep using the address the user typed. The validator runs for local and external registration, admin create/update user, and email changes.Put the following classes in your
EntityFrameworkCoreproject.- The canonicalization rule:
namespace MyProject.Identity; public static class EmailCanonicalizer { public const string PropertyName = "CanonicalEmail"; public static string? Canonicalize(string? email) { if (string.IsNullOrWhiteSpace(email)) { return null; } email = email.Trim().ToLowerInvariant(); var atIndex = email.LastIndexOf('@'); if (atIndex <= 0 || atIndex == email.Length - 1) { return email; } var localPart = email[..atIndex]; var domain = email[(atIndex + 1)..]; var plusIndex = localPart.IndexOf('+'); if (plusIndex > 0) { localPart = localPart[..plusIndex]; } if (domain is "gmail.com" or "googlemail.com") { localPart = localPart.Replace(".", string.Empty); domain = "gmail.com"; } return $"{localPart}@{domain}"; } }- Map it to a column in
YourProjectEfCoreEntityExtensionMappings.Configure(), insideOneTimeRunner.Run, then add a new migration:
ObjectExtensionManager.Instance .MapEfCoreProperty<IdentityUser, string>( EmailCanonicalizer.PropertyName, (entityBuilder, propertyBuilder) => { propertyBuilder.HasMaxLength(256); entityBuilder.HasIndex("TenantId", EmailCanonicalizer.PropertyName); } );- The checker and the validator:
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Repositories; using Volo.Abp.Identity; namespace MyProject.Identity; public class CanonicalEmailChecker : ITransientDependency { private readonly IRepository<IdentityUser, Guid> _userRepository; public CanonicalEmailChecker(IRepository<IdentityUser, Guid> userRepository) { _userRepository = userRepository; } public virtual async Task<bool> IsTakenAsync(string? email, Guid? excludedUserId = null) { var canonicalEmail = EmailCanonicalizer.Canonicalize(email); if (canonicalEmail == null) { return false; } var queryable = await _userRepository.GetQueryableAsync(); return await queryable.AnyAsync(u => u.Id != excludedUserId && EF.Property<string>(u, EmailCanonicalizer.PropertyName) == canonicalEmail); } }using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Volo.Abp.Data; using IdentityUser = Volo.Abp.Identity.IdentityUser; namespace MyProject.Identity; public class CanonicalEmailUserValidator : IUserValidator<IdentityUser> { private readonly CanonicalEmailChecker _canonicalEmailChecker; public CanonicalEmailUserValidator(CanonicalEmailChecker canonicalEmailChecker) { _canonicalEmailChecker = canonicalEmailChecker; } public async Task<IdentityResult> ValidateAsync(UserManager<IdentityUser> manager, IdentityUser user) { var currentCanonicalEmail = user.GetProperty<string>(EmailCanonicalizer.PropertyName); var canonicalEmail = EmailCanonicalizer.Canonicalize(user.Email); user.SetProperty(EmailCanonicalizer.PropertyName, canonicalEmail); // Only check when the value changes, so existing duplicate accounts // can still confirm their email, reset their password and log in. if (canonicalEmail == null || canonicalEmail == currentCanonicalEmail || !manager.Options.User.RequireUniqueEmail) { return IdentityResult.Success; } return await _canonicalEmailChecker.IsTakenAsync(user.Email, user.Id) ? IdentityResult.Failed(manager.ErrorDescriber.DuplicateEmail(user.Email!)) : IdentityResult.Success; } }Register the validator in
PreConfigureServicesof yourEntityFrameworkCoremodule:PreConfigure<IdentityBuilder>(builder => { builder.AddUserValidator<CanonicalEmailUserValidator>(); });- Fill the column for existing users. This runs with your
DbMigrator, for the host and every tenant:
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Volo.Abp.Data; using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Repositories; using Volo.Abp.Identity; using Volo.Abp.Uow; namespace MyProject.Identity; public class CanonicalEmailDataSeedContributor : IDataSeedContributor, ITransientDependency { private readonly IRepository<IdentityUser, Guid> _userRepository; private readonly IUnitOfWorkManager _unitOfWorkManager; public CanonicalEmailDataSeedContributor( IRepository<IdentityUser, Guid> userRepository, IUnitOfWorkManager unitOfWorkManager) { _userRepository = userRepository; _unitOfWorkManager = unitOfWorkManager; } public async Task SeedAsync(DataSeedContext context) { Guid? lastId = null; while (true) { using var uow = _unitOfWorkManager.Begin(requiresNew: true); var queryable = await _userRepository.GetQueryableAsync(); var users = await queryable .Where(u => lastId == null || u.Id.CompareTo(lastId.Value) > 0) .Where(u => EF.Property<string>(u, EmailCanonicalizer.PropertyName) == null) .OrderBy(u => u.Id) .Take(1000) .ToListAsync(); if (users.Count == 0) { await uow.CompleteAsync(); return; } foreach (var user in users) { user.SetProperty(EmailCanonicalizer.PropertyName, EmailCanonicalizer.Canonicalize(user.Email)); } await _userRepository.UpdateManyAsync(users); await uow.CompleteAsync(); lastId = users[^1].Id; } } }- One more page needs a change, in your
AuthServerproject. The change email link page catches the duplicate email error, but the changes made before the check are still saved. This override checks before calling the original page:
using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using MyProject.Identity; using Volo.Abp.Account; using Volo.Abp.Account.Public.Web.Pages.Account; using Volo.Abp.DependencyInjection; using Volo.Abp.Identity; namespace MyProject.Pages.Account; [Dependency(ReplaceServices = true)] [ExposeServices(typeof(ChangeEmailModel))] public class CanonicalEmailChangeEmailModel : ChangeEmailModel { private readonly CanonicalEmailChecker _canonicalEmailChecker; public CanonicalEmailChangeEmailModel( IAccountAppService accountAppService, CanonicalEmailChecker canonicalEmailChecker) : base(accountAppService) { _canonicalEmailChecker = canonicalEmailChecker; } public override async Task<IActionResult> OnGetAsync() { var user = await UserManager.FindSharedUserByIdAsync(UserId.ToString()); if (user != null && user.Email != NewEmailAddress) { using (CurrentTenant.Change(user.TenantId)) { if (await _canonicalEmailChecker.IsTakenAsync(NewEmailAddress, user.Id)) { ReturnUrl = await GetRedirectUrlAsync(ReturnUrl, ReturnUrlHash); var error = UserManager.ErrorDescriber.DuplicateEmail(NewEmailAddress); Alerts.Warning(GetLocalizeExceptionMessage(new AbpIdentityResultException(IdentityResult.Failed(error)))); return Page(); } } } return await base.OnGetAsync(); } }The index above is not unique, so two sign-ups that submit at the same moment can still both pass the check. If you want the database to block that too, clean up the existing duplicates after step 4, then make the index unique (PostgreSQL 15+):
entityBuilder.HasIndex("TenantId", EmailCanonicalizer.PropertyName) .IsUnique() .AreNullsDistinct(false) .HasFilter("\"CanonicalEmail\" IS NOT NULL AND NOT \"IsDeleted\"");AreNullsDistinct(false)makes it work for host users too (theirTenantIdis null). The filter skips empty values and soft-deleted users.This works with the default
Isolateduser sharing strategy.Thanks
Markdown supported.Copy, paste, or drag & drop images and files (max 100 MB per file, 100 MB total per post) -
0
[maliming] said: Hi,
There's no built-in option for this right now. We'll pass it on to the team as a feature request.
You can add it in your own solution today. Store a canonical form of the email in an extra column, and check it in a custom
IUserValidator. Email,NormalizedEmail, login, confirmation and password reset keep using the address the user typed. The validator runs for local and external registration, admin create/update user, and email changes.Put the following classes in your
EntityFrameworkCoreproject.- The canonicalization rule:
namespace MyProject.Identity; public static class EmailCanonicalizer { public const string PropertyName = "CanonicalEmail"; public static string? Canonicalize(string? email) { if (string.IsNullOrWhiteSpace(email)) { return null; } email = email.Trim().ToLowerInvariant(); var atIndex = email.LastIndexOf('@'); if (atIndex <= 0 || atIndex == email.Length - 1) { return email; } var localPart = email[..atIndex]; var domain = email[(atIndex + 1)..]; var plusIndex = localPart.IndexOf('+'); if (plusIndex > 0) { localPart = localPart[..plusIndex]; } if (domain is "gmail.com" or "googlemail.com") { localPart = localPart.Replace(".", string.Empty); domain = "gmail.com"; } return $"{localPart}@{domain}"; } }- Map it to a column in
YourProjectEfCoreEntityExtensionMappings.Configure(), insideOneTimeRunner.Run, then add a new migration:
ObjectExtensionManager.Instance .MapEfCoreProperty<IdentityUser, string>( EmailCanonicalizer.PropertyName, (entityBuilder, propertyBuilder) => { propertyBuilder.HasMaxLength(256); entityBuilder.HasIndex("TenantId", EmailCanonicalizer.PropertyName); } );- The checker and the validator:
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Repositories; using Volo.Abp.Identity; namespace MyProject.Identity; public class CanonicalEmailChecker : ITransientDependency { private readonly IRepository<IdentityUser, Guid> _userRepository; public CanonicalEmailChecker(IRepository<IdentityUser, Guid> userRepository) { _userRepository = userRepository; } public virtual async Task<bool> IsTakenAsync(string? email, Guid? excludedUserId = null) { var canonicalEmail = EmailCanonicalizer.Canonicalize(email); if (canonicalEmail == null) { return false; } var queryable = await _userRepository.GetQueryableAsync(); return await queryable.AnyAsync(u => u.Id != excludedUserId && EF.Property<string>(u, EmailCanonicalizer.PropertyName) == canonicalEmail); } }using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Volo.Abp.Data; using IdentityUser = Volo.Abp.Identity.IdentityUser; namespace MyProject.Identity; public class CanonicalEmailUserValidator : IUserValidator<IdentityUser> { private readonly CanonicalEmailChecker _canonicalEmailChecker; public CanonicalEmailUserValidator(CanonicalEmailChecker canonicalEmailChecker) { _canonicalEmailChecker = canonicalEmailChecker; } public async Task<IdentityResult> ValidateAsync(UserManager<IdentityUser> manager, IdentityUser user) { var currentCanonicalEmail = user.GetProperty<string>(EmailCanonicalizer.PropertyName); var canonicalEmail = EmailCanonicalizer.Canonicalize(user.Email); user.SetProperty(EmailCanonicalizer.PropertyName, canonicalEmail); // Only check when the value changes, so existing duplicate accounts // can still confirm their email, reset their password and log in. if (canonicalEmail == null || canonicalEmail == currentCanonicalEmail || !manager.Options.User.RequireUniqueEmail) { return IdentityResult.Success; } return await _canonicalEmailChecker.IsTakenAsync(user.Email, user.Id) ? IdentityResult.Failed(manager.ErrorDescriber.DuplicateEmail(user.Email!)) : IdentityResult.Success; } }Register the validator in
PreConfigureServicesof yourEntityFrameworkCoremodule:PreConfigure<IdentityBuilder>(builder => { builder.AddUserValidator<CanonicalEmailUserValidator>(); });- Fill the column for existing users. This runs with your
DbMigrator, for the host and every tenant:
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Volo.Abp.Data; using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Repositories; using Volo.Abp.Identity; using Volo.Abp.Uow; namespace MyProject.Identity; public class CanonicalEmailDataSeedContributor : IDataSeedContributor, ITransientDependency { private readonly IRepository<IdentityUser, Guid> _userRepository; private readonly IUnitOfWorkManager _unitOfWorkManager; public CanonicalEmailDataSeedContributor( IRepository<IdentityUser, Guid> userRepository, IUnitOfWorkManager unitOfWorkManager) { _userRepository = userRepository; _unitOfWorkManager = unitOfWorkManager; } public async Task SeedAsync(DataSeedContext context) { Guid? lastId = null; while (true) { using var uow = _unitOfWorkManager.Begin(requiresNew: true); var queryable = await _userRepository.GetQueryableAsync(); var users = await queryable .Where(u => lastId == null || u.Id.CompareTo(lastId.Value) > 0) .Where(u => EF.Property<string>(u, EmailCanonicalizer.PropertyName) == null) .OrderBy(u => u.Id) .Take(1000) .ToListAsync(); if (users.Count == 0) { await uow.CompleteAsync(); return; } foreach (var user in users) { user.SetProperty(EmailCanonicalizer.PropertyName, EmailCanonicalizer.Canonicalize(user.Email)); } await _userRepository.UpdateManyAsync(users); await uow.CompleteAsync(); lastId = users[^1].Id; } } }- One more page needs a change, in your
AuthServerproject. The change email link page catches the duplicate email error, but the changes made before the check are still saved. This override checks before calling the original page:
using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using MyProject.Identity; using Volo.Abp.Account; using Volo.Abp.Account.Public.Web.Pages.Account; using Volo.Abp.DependencyInjection; using Volo.Abp.Identity; namespace MyProject.Pages.Account; [Dependency(ReplaceServices = true)] [ExposeServices(typeof(ChangeEmailModel))] public class CanonicalEmailChangeEmailModel : ChangeEmailModel { private readonly CanonicalEmailChecker _canonicalEmailChecker; public CanonicalEmailChangeEmailModel( IAccountAppService accountAppService, CanonicalEmailChecker canonicalEmailChecker) : base(accountAppService) { _canonicalEmailChecker = canonicalEmailChecker; } public override async Task<IActionResult> OnGetAsync() { var user = await UserManager.FindSharedUserByIdAsync(UserId.ToString()); if (user != null && user.Email != NewEmailAddress) { using (CurrentTenant.Change(user.TenantId)) { if (await _canonicalEmailChecker.IsTakenAsync(NewEmailAddress, user.Id)) { ReturnUrl = await GetRedirectUrlAsync(ReturnUrl, ReturnUrlHash); var error = UserManager.ErrorDescriber.DuplicateEmail(NewEmailAddress); Alerts.Warning(GetLocalizeExceptionMessage(new AbpIdentityResultException(IdentityResult.Failed(error)))); return Page(); } } } return await base.OnGetAsync(); } }The index above is not unique, so two sign-ups that submit at the same moment can still both pass the check. If you want the database to block that too, clean up the existing duplicates after step 4, then make the index unique (PostgreSQL 15+):
entityBuilder.HasIndex("TenantId", EmailCanonicalizer.PropertyName) .IsUnique() .AreNullsDistinct(false) .HasFilter("\"CanonicalEmail\" IS NOT NULL AND NOT \"IsDeleted\"");AreNullsDistinct(false)makes it work for host users too (theirTenantIdis null). The filter skips empty values and soft-deleted users.This works with the default
Isolateduser sharing strategy.Thanks
We are aware that there are a number of solutions for this, and we have already implemented some of them. On the other hand, since we have many products that rely on the same infrastructure, we would prefer a centralized solution. We look forward to you developing this feature.
BR,
Markdown supported.Copy, paste, or drag & drop images and files (max 100 MB per file, 100 MB total per post) -
0
Hi,
That makes sense. A shared option in the framework is better than each product keeping its own copy.
We'll track this as a feature request for the Identity module. I'll update this ticket when there's progress.
Thanks
Markdown supported.Copy, paste, or drag & drop images and files (max 100 MB per file, 100 MB total per post) -
0
[maliming] said: Hi,
That makes sense. A shared option in the framework is better than each product keeping its own copy.
We'll track this as a feature request for the Identity module. I'll update this ticket when there's progress.
Thanks
Thanks, We are looking forward to it with excitement!
Markdown supported.Copy, paste, or drag & drop images and files (max 100 MB per file, 100 MB total per post) -
0
Hi,
Sorry for the change of plan. We discussed this internally, and we don't plan to add a built-in option for this.
An alias check only catches different addresses of the same mailbox, so it can't solve the multi-account problem by itself. Disposable email services give a new mailbox for each sign-up, and anyone with their own domain can create as many addresses as they want. These mailboxes receive the verification code like any other. The alias rules also depend on the mail provider: removing the
+tagfor every domain can merge mailboxes that are really different.Stopping multiple accounts needs more than an email rule, for example blocking disposable domains, phone verification, captcha, limits per IP and rules around trials. Each application needs a different mix, so there is no general solution we can add to the framework. We think these rules fit better in the application, where you can choose the ones you need. The workaround from our earlier reply already covers the alias part, and you can put it in a shared module so all your products use the same rules.
For limits per IP, you can check the Operation Rate Limiting module (ABP 10.3 and later). For example, you can add a
PartitionByClientIp()rule to theAccount.SendEmailConfirmationCodepolicy to limit how many sign-up codes one IP can request.Thanks
Markdown supported.Copy, paste, or drag & drop images and files (max 100 MB per file, 100 MB total per post)