【问题标题】:Setting a post-authentication View for Windows Authentication为 Windows 身份验证设置身份验证后视图
【发布时间】:2013-08-13 01:09:18
【问题描述】:

我有一个 MVC4 Intranet 应用程序(使用默认模板)。我使用 Windows 身份验证作为我的登录系统,但是,我希望能够在用户第一次注册网站时从他们那里获取一些详细信息。

用例

  1. 第一次用户使用其 AD 登录进行身份验证(当前有效)。他们会看到“输入您的详细信息”视图。
  2. 第二次用户使用其 AD 登录进行身份验证。他们被带走 直接进入主屏幕。

干杯, 戴夫

【问题讨论】:

  • 创建一个自定义授权属性,您可以在其中检查数据库中是否保存了用户的详细信息,如果没有,将用户重定向到“输入您的详细信息”视图。
  • 你能用一些轻量级的代码示例发布一个答案吗?我希望有一种方法可以将他们引导到授权视图(就像 Forms Auth 一样)。如果我要实现自定义属性,我还需要知道如何从 Windows auth 获取他们的详细信息。

标签: c# asp.net-mvc asp.net-mvc-4 windows-authentication


【解决方案1】:

像这样创建一个自定义 AuthorizeAttribute:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    private UnitOfWork _unitOfWork = new UnitOfWork();

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = false;
        var username = httpContext.User.Identity.Name;
        // Some code to find the user in the database...
        var user = _unitOfWork.UserRepository.Find(username);
        if(user != null)
        {
           // Check if there are Details for the user in the database
           if(user.HasDetails)
           {
             isAuthorized = true;
           }
        }


        return isAuthorized;
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {            
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        if (!AuthorizeCore(filterContext.HttpContext))
        {
           // If not authorized, redirect to the Details action 
           // of the Account controller... 

           var action = filterContext.RouteData.Values["action"];
           if(filterContext.Controller is AccountController 
             && action.Equals("Details"))
           {
             // Do nothing
           }
           else
           {
             filterContext.Result = new RedirectToRouteResult(
               new System.Web.Routing.RouteValueDictionary {
                 {"controller", "Account"}, {"action", "Details"}
               }
             );
           }               
        }
    }
}

然后,您可以像这样在控制器中使用它:

[MyAuthorize]
public class HomeController : Controller
{
}

或者,您可以将其注册为 Global.asax 文件中的全局操作过滤器,如下所示:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new MyAuthorizeAttribute());
}

【讨论】:

  • 顺便说一句,您能否添加一个签入以验证所调用的操作不是详细信息操作?否则我们会得到一个循环。
猜你喜欢
  • 2016-03-12
  • 2010-10-05
  • 2013-10-30
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 2023-03-22
相关资源
最近更新 更多