2014-03-27 178 views
1

我目前正在研究ASP.NET MVC4網站。 而在那個網站上,我不想讓某個角色的用戶被允許運行代碼。 我使用下面的代碼:ASP.NET IIS用戶角色身份驗證

[Authorize(Roles = GROUP)] 
    public void Auth() 
    { 
     /* if user is in the domain and signed in 
     * and a member of the above group 
     * they will come here */ 

     username = User.Identity.Name; 

     //Do somthing 
    } 

來完成這項工程,但是當用戶不是域和/或組的一部分,它西港島線提示輸入用戶名和密碼。是否可以跳過提示並重定向該用戶?

這個網站是建立在一個IIS 8身份驗證設置爲Windows身份驗證

+0

[Rú? – Neel

+0

是的,在身份驗證設置爲Windows身份驗證的IIS 8中 – Msmit1993

回答

3

嗯,我可以創建自定義授權屬性並實現HandleUnauthorizedRequest方法來解決這個問題。

public class CustomAutorizeAttribute : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     // do authorization logic 
     // ... 


     return (/* isAuthorized */); 
    } 


    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    { 
     UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext); 


     filterContext.Result = new RedirectResult(urlHelper.Action("Index", "Error")); 
    } 
} 

欲瞭解更多信息,請閱讀使用Windows身份驗證How to: Create a Custom Authorization Attribute

+1

這是正確的授權方式,因爲您想告訴用戶您沒有權限。 – Shaz

1

使用

[Authorize(Roles = GROUP)] 
    [HandleError(ExceptionType = typeof(UnauthorizedAccessException), View = "ApplicationError")] 
    public void Auth() 
    { 
     /* if user is in the domain and signed in 
     * and a member of the above group 
     * they will come here */ 

     username = User.Identity.Name; 

     //Do somthing 
    } 

在那裏你可以sepcify視圖未經授權的訪問用戶

+0

感謝您的建議,但它仍會提示輸入用戶名和密碼 – Msmit1993