登录后仍然可以进入登录页面

时间:2020-06-15 11:54:06

标签: asp.net-core

I,m使用启用了“个人用户身份验证”的默认“模型-视图-控制器”模板。问题是登录后,我仍然可以进入登录页面。如何预防呢?

1 个答案:

答案 0 :(得分:1)

您可以自定义中间件以在用户登录并访问登录页面时重定向。

RedirectMiddleware.cs

public class RedirectMiddleware
{
    private readonly RequestDelegate _next;

    public RedirectMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if(context.Request.Path == "/Identity/Account/Login")
        {
            if (context.User.Identity.IsAuthenticated)
            {
                context.Response.Redirect("/Home/Index");
            }
        }
        await _next.Invoke(context);
    }
}

Startup.cs

app.UseMiddleware<RedirectMiddleware>();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
});

直接在Login OnGetAsync处理程序中进行重定向:

public async Task OnGetAsync(string returnUrl = null)
    {
        if (!string.IsNullOrEmpty(ErrorMessage))
        {
            ModelState.AddModelError(string.Empty, ErrorMessage);
        }
        if (User.Identity.IsAuthenticated)
        {
            Response.Redirect("/Home/Index");
        }
        returnUrl = returnUrl ?? Url.Content("~/");

        // Clear the existing external cookie to ensure a clean login process
        await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

        ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

        ReturnUrl = returnUrl;
    }