2014-03-27 173 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