[英]How to display custom error if authorization fails in ASP.NET MVC
Trying to figure out how to avoid requesting username and password when a controller action is called that has an Authorize
header and simply redirect to a View. 试图弄清楚在调用具有
Authorize
标头并直接重定向到View的控制器操作时如何避免请求用户名和密码。
In my web.config I have 在我的web.config中
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" cacheRolesInCookie="false">
<providers>
<clear />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
Then, in my controller, I am prefixing an action as follows 然后,在控制器中,我为操作添加了以下前缀
[Authorize(Roles = "DOMAIN\\Group")]
public ActionResult Index()
{
...controller action code here
}
If I set it to a DOMAIN\\Group that I belong to, then the application works just as expected. 如果将其设置为我所属的DOMAIN \\ Group,则该应用程序将按预期运行。 If I change it to a bogus group for testing, I am presented with a username and password dialog.
如果我将其更改为假组进行测试,则会看到一个用户名和密码对话框。 Obviously, authentication will never happen.
显然,身份验证永远不会发生。 If I click cancel in the dialog, I get redirected to the 401 error page.
如果单击对话框中的“取消”,则会重定向到401错误页面。
What I would LIKE to do is, since by definition in the web.config file only windows users can connect, if that windows user is not in the chosen group, simply redirect to a particular View rather than prompting for a username and password. 我想做的是,由于在web.config文件中定义,只有Windows用户可以连接,如果该Windows用户不在所选组中,则只需重定向到特定的View,而不提示输入用户名和密码。
You can create a custom attribute and override HandleUnauthorizedRequest . 您可以创建一个自定义属性并覆盖HandleUnauthorizedRequest 。 Then you redirect to a custom page, if authorization fails,
然后,您重定向到自定义页面,如果授权失败,
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Common", action = "AccessDenied" }));
}
}
}
[CustomAuthorize(Roles = "DOMAIN\\Group")]
public ActionResult Index()
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.