向 ASP.NET MVC 身份验证添加额外步骤

Adding extra step to ASP.NET MVC authentication

我有一个使用标准表单身份验证的 MVC 5 网站运行。

但是我需要在用户的登录过程中添加一个额外的步骤。用户通过身份验证后,我们会查看他们是否有权访问多个办公室。如果他们这样做,我们需要向他们展示办公室列表,他们必须选择一个。

这是一个强制性步骤,在他们完成之前不能被视为已登录。

我们需要创建自己的身份验证还是应该向 BaseController 添加检查?

您可以扩展内置身份验证的实现:

public class OfficeSelectionAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var result = base.AuthorizeCore(httpContext);

        if (result)
        {
            if (IsOfficeSelected())
            {
                return true;
            }

            httpContext.Response.RedirectToRoute("OfficeSelection Route");
            httpContext.Response.Flush();
        }

        return false;
    }

    private bool IsOfficeSelected()
    {
        //office selection check
    }
}

那么您需要使用此过滤器而不是默认过滤器:

[OfficeSelectionAuthorize]
public class AccountController : Controller
{
    //action methods
}