我目前正在开发 ASP.NET MVC4 网站。 在该网站中,我不希望属于特定角色的用户被允许运行代码。 我使用以下代码:
[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 身份验证
请您参考如下方法:
好吧,我会创建一个自定义授权属性并实现 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"));
}
}
