Force user change password when loading any webpage

后端 未结 2 1889
予麋鹿
予麋鹿 2021-01-27 23:33

I am using ASP.net core 2.0. I added a flag column called IsChangePassword to my AspNetUsers table and to my ApplicationUser class. The idea is to force the user to change their

2条回答
  •  不知归路
    2021-01-28 00:13

    You need a resource filter, which you'll need to inject with both UserManager and IUrlHelperFactory. The former will obviously be used to check the value of IsChangePassword, while the latter will be necessary to check the current URL against your chosen redirect URL, to prevent an endless redirect loop. Simply:

    public class ChangePasswordResourceFilter : IAsyncResourceFilter
    {
        private readonly UserManager _userManager;
        private readonly IUrlHelperFactory _urlHelperFactory;
    
        public ChangePasswordResourceFilter(UserManager userManager, IUrlHelperFactory urlHelperFactory)
        {
            _userManager = userManager;
            _urlHelperFactory = urlHelperFactory;
        }
    
        public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
        {
            var urlHelper = _urlHelperFactory.GetUrlHelper(context);
            var redirectUrl = urlHelper.Page("~/PasswordChange");
            var currentUrl = context.HttpContext.Request.Path;
    
            if (redirectUrl != currentUrl)
            {
                var user = await _userManager.GetUserAsync(context.HttpContext.User);
                if (user?.IsChangePassword ?? false)
                {
                    context.Result = new RedirectResult(redirectUrl);
                }
            }
    
            await next();
        }
    }
    

    Then, in Startup.ConfigureServices:

    services.AddScoped();
    
    ...
    
    services.AddMvc(o =>
    {
        o.Filters.Add(typeof(ChangePasswordResourceFilter));
    });
    

提交回复
热议问题