2016-01-21 59 views
0

我有一個MVC5網站,我希望任何人都能夠從受限制的管理區域以外查看站點。我已經創建了一個過濾器來檢查我已經應用到管理控制器的用戶AD組,並且這個工作非常好。授權頁面上的MVC Windows身份驗證401

這些問題是爲人們查看主站點,如果它閒置一段時間,他們會在導航到頁面時收到未經授權的響應。一旦他們刷新它的罰款,並讓他們回到頁面。

的Web.Config在

<authentication mode="Windows" /> 

以下如果我刪除此則問題消失,但管理控制器不工作,因爲在我的自定義過濾器沒有發現Windows用戶。

的自定義過濾器只檢查一個AD組:

var groupList = GetGroupList(); 

     if (base.AuthorizeCore(httpContext)) 
     { 
      if (string.IsNullOrEmpty(groupList)) 
       return true; 

      var groups = groupList.Split(',').ToList(); 

      var context = new PrincipalContext(ContextType.Domain, "MYDOMAIN"); 

      var userPrincipal = UserPrincipal.FindByIdentity(
       context, 
       IdentityType.SamAccountName, 
       httpContext.User.Identity.Name); 

      if (userPrincipal == null) 
       return false; 

      try 
      { 
       foreach (var group in groups) 
        if (userPrincipal.IsMemberOf(context, 
         IdentityType.Name, 
         group)) 
         return true; 
      } 
      catch 
      { 
       return false; 
      } 

回答

0

我想你想重定向未授權訪問一些錯誤頁面上的用戶。 你可以通過在web配置中添加這個來做到這一點。 (AccessDenied.aspx頁面中,你已經寫了對於聯合國授權的用戶訪問的消息)

 <customErrors defaultRedirect="ErrorPage.aspx" mode="On"> 
    <error statusCode="401" redirect="AccessDenied.aspx" />  
    </customErrors> 

,或者你可以做到這一點在Global.asax文件

 protected void Application_AuthenticateRequest(Object sender, 
               EventArgs e) 
     { 
     if (!Request.IsAuthenticated) Response.Redirect(
             "AccessDenied.aspx"); 
    } 
+0

由於某些原因,即使控制器沒有[Authorize]屬性,我仍然得到重定向到訪問被拒絕的頁面,任何人都應該能夠查看頁面。 – tonyjoanes

0

在我最近的經驗,與AD工作從一個IIS框中,我使用一個完全相同的過濾器來按AD組進行過濾。雖然我的過濾器是相同的,但我注意到httpContext.User.Identity.Name不會像控制器中的「正常」匿名網站那樣返回用戶。

,並使其自動地通過AD用戶SANS授權的登錄界面,我必須禁用匿名身份驗證,啓用Windows驗證,設置<identity impersonate="true" />及用途:

UserPrincipal adUser = null; 
     using (HostingEnvironment.Impersonate()) 
     { 
      var userContext = System.Web.HttpContext.Current.User.Identity; 
      PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["AllowedDomain"], null, 
       ContextOptions.Negotiate | ContextOptions.SecureSocketLayer); 
      adUser = UserPrincipal.FindByIdentity(ctx, userContext.Name); 
     } 
// and work with 'adUser' from here on in my controllers... 

我的應用纔剛剛進入生產內部,但現在我沒有遇到你的假期「超時」問題。你的web.config中有沒有多餘的表單auth標籤?我也不得不在我的web.config中設置<sessionState mode="InProc" />