Disable User in ASPNET identity 2.0

后端 未结 10 1151
谎友^
谎友^ 2020-11-30 23:50

I am looking for a way to disable the user instead of deleting them from the system, this is to keep the data integrity of the related data. But seems ASPNET identity only

10条回答
  •  旧巷少年郎
    2020-12-01 00:03

    Ozz is correct, however it may be adviseable to look at the base class and see if you can find a method that is checked for all signin angles - I think it might be CanSignIn?

    Now that MS is open source you can see their implementation:

    https://github.com/aspnet/AspNetCore/blob/master/src/Identity/src/Identity/SignInManager.cs

    (Url has changed to:

    https://github.com/aspnet/AspNetCore/blob/master/src/Identity/Core/src/SignInManager.cs)

        public class CustomSignInManager : SignInManager  
    {
        public CustomSignInManager(UserManager userManager,
            IHttpContextAccessor contextAccessor,
            IUserClaimsPrincipalFactory claimsFactory,
            IOptions optionsAccessor,
            ILogger> logger,
            IAuthenticationSchemeProvider schemes) : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes)
        {
    
        }
    
    
        public override async Task CanSignInAsync(ApplicationUser user)
        {
            if (Options.SignIn.RequireConfirmedEmail && !(await UserManager.IsEmailConfirmedAsync(user)))
            {
                Logger.LogWarning(0, "User {userId} cannot sign in without a confirmed email.", await UserManager.GetUserIdAsync(user));
                return false;
            }
            if (Options.SignIn.RequireConfirmedPhoneNumber && !(await UserManager.IsPhoneNumberConfirmedAsync(user)))
            {
                Logger.LogWarning(1, "User {userId} cannot sign in without a confirmed phone number.", await UserManager.GetUserIdAsync(user));
                return false;
            }
    
            if (UserManager.FindByIdAsync(user.Id).Result.IsEnabled == false)
            {
                Logger.LogWarning(1, "User {userId} cannot sign because it's currently disabled", await UserManager.GetUserIdAsync(user));
                return false;
            }
    
            return true;
        }
    }
    

    Also consider overriding PreSignInCheck, which also calls CanSignIn:

    protected virtual async Task PreSignInCheck(TUser user)
            {
                if (!await CanSignInAsync(user))
                {
                    return SignInResult.NotAllowed;
                }
                if (await IsLockedOut(user))
                {
                    return await LockedOut(user);
                }
                return null;
            }
    

提交回复
热议问题