简体   繁体   English

在 ASP.NET Core 中首次登录时强制重定向到另一个页面

[英]Force Redirect to Another Page when First Time Login in ASP.NET Core

currently I'm building web apps for local.目前我正在为本地构建网络应用程序。 When I create new user, I'm setup the user with Default Password.当我创建新用户时,我使用默认密码设置用户。 And I want to, if the User login with the Default Password it will redirect to Change Password Page.我想,如果用户使用默认密码登录,它将重定向到更改密码页面。 And User will not be able to access any page until they change the password.并且用户在更改密码之前将无法访问任何页面。

My current workaround is checking in each controller, is there any Smart way to do this?我目前的解决方法是检查每个控制器,是否有任何智能方法可以做到这一点?

Here's some code after doing login这是登录后的一些代码

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login([FromForm] LoginViewModel vm, string returnUrl = null)
{
    if (ModelState.IsValid)
    {
        var result = await repository.Login(vm);
        if (result.IsSuccess)
        {
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, result.Data,
                new AuthenticationProperties
                {
                    IssuedUtc = DateTime.UtcNow,
                    ExpiresUtc = DateTime.UtcNow.AddDays(1),
                    IsPersistent = false
                });

            if (vm.Password != Password.DefaultPassword)
            {
                return RedirectToLocal(returnUrl);
            }
            else
            {
                return RedirectToAction(nameof(UserController.NewPassword));
            }
        }
        else
        {
            ViewBag.ErrorMessage = result.ErrorMessage;
        }
    }

    return View(vm);
}

For the other Controller, we always check the Password from session.对于另一个控制器,我们总是从会话中检查密码。 If the Password is same as Default Password we redirect it to NewPassword Page如果密码与默认密码相同,我们会将其重定向到NewPassword页面

Thanks in advance!提前致谢!

As @JHBonarius said, my current workaround now is to use Custom Middleware for Redirecting to New Password Page.正如@JHBonarius 所说,我现在的解决方法是使用自定义中间件重定向到新密码页面。

My middleware look like this:我的中间件如下所示:

public class CheckPasswordMiddleware
{
    private readonly RequestDelegate next;

    public CheckPasswordMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Path != "/User/NewPassword" && context.User.Identity.IsAuthenticated)
        {
            var userId = context.User.Identity.GetUserId();
            if (!string.IsNullOrEmpty(userId))
            {
                var dbContext = context.RequestServices.GetRequiredService<DatabaseContext>();
                var passwordHash = await dbContext.User.Where(x => x.Id.ToLower() == userId.ToLower()).Select(x => x.Password).FirstOrDefaultAsync();
                if (Hash.Verify(Password.DefaultPassword, passwordHash))
                {
                    context.Response.Redirect("/User/NewPassword");
                }
            }
        }

        await next(context);
    }
}

and now I can get rid the check in my other controller, and my Login will just look like this:现在我可以摆脱其他控制器中的检查,我的登录将如下所示:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login([FromForm] LoginViewModel vm, string returnUrl = null)
{
    if (ModelState.IsValid)
    {
        var result = await repository.Login(vm);
        if (result.IsSuccess)
        {
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, result.Data,
                new AuthenticationProperties
                {
                    IssuedUtc = DateTime.UtcNow,
                    ExpiresUtc = DateTime.UtcNow.AddDays(1),
                    IsPersistent = false
                });
            return RedirectToLocal(returnUrl);
        }
        else
        {
            ViewBag.ErrorMessage = result.ErrorMessage;
        }
    }

    return View(vm);
}

Hope this help anyone who want to achieve the same goals.希望这可以帮助任何想要实现相同目标的人。

Thanks!谢谢!

You can store user password using session as below您可以使用session存储用户密码,如下所示

HttpContext.Session.SetString("Password", vm.password);

Then create a filter to check if the user login with the Default Password or not然后创建一个过滤器来检查用户是否使用默认密码登录

public class PasswordFilter: IAuthorizationFilter
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ISession _session;
        public PasswordFilter(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            _session = _httpContextAccessor.HttpContext.Session;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {

            if (_session.GetString("Password") == Password.DefaultPassword)
            {
                context.Result = new RedirectResult(nameof(UserController.NewPassword));

            }
        }
    }

Finally, you can use this filter by adding this attribute to your controllers最后,您可以通过将此属性添加到控制器来使用此过滤器

[TypeFilter(typeof(PasswordFilter))]

I hope this approach achieves your goal.我希望这种方法可以实现您的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Asp.net 核心 mvc 中登录后重定向到同一页面 - Redirect to same page after Login in Asp.net core mvc ASP.NET 核心重定向到登录页面而不返回 url - ASP.NET Core redirect to login page without return url ASP.Net 核心 MVC6 未授权时重定向到登录 - ASP.Net core MVC6 Redirect to Login when not authorised 在 ASP.NET 核心中未经授权时重定向到登录 - Redirect to login when unauthorized in ASP.NET Core 使用 ASP.net 核心 C# 在 MVC 应用程序中 session 过期或空闲时间后重定向到登录页面 - Redirect to Login page after session expire or idle time in MVC application using ASP.net core C# 如何在 .ASP.NET Core MVC 中使用多个登录页面和未经授权的用户重定向不同的登录页面 - How to use multiple login pages in .ASP.NET Core MVC and unauthorized user redirect different login page 在 Asp.net 内核中使用 JQuery 重定向页面 - Redirect Page With JQuery In Asp.net Core 带有 ASP.NET 内核 (MVC) 的登录页面 - Login Page with ASP.NET Core (MVC) 如何强制启动 Asp.Net Core 3.0 应用程序以使用身份登录页面 - How to force start Asp.Net Core 3.0 application to use Identity Login Page 登录 Asp.net 核心 mvc 后如何重定向到上次访问的页面 - How to Redirect to Last Visited page After Login in Asp.net core mvc
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM