[英]How do I redirect to a not-authorized page instead of the login page when the user is already logged in?
How do I set my Authorize(Roles="blah") token to redirect to a "You're not authorized to do this" when a user is already logged in but isn't in the correct role? 当用户已经登录但角色不正确时,如何设置Authorize(Roles =“ blah”)令牌以重定向到“您无权执行此操作”? Currently it redirects to the login page which isn't what we're after. 当前它重定向到登录页面,这不是我们想要的。 We feel that it's confusing for the user to be redirected to this page as they're already logged in. In the event however they're not logged in, it should redirect to the login page. 我们认为用户已经登录到该页面会使用户感到困惑。但是,如果他们尚未登录,则应将其重定向到登录页面。
The way AuthorizeAttribute is designed is that it will first look if the user is authenticated and then look if he is in role. 设计AuthorizeAttribute的方式是,它首先将查看用户是否已通过身份验证,然后再查看用户是否具有角色。 If any of these conditions aren't satisfied it will simply return return a HttpUnauthorizedResult which in turn will set the response code to 401. To achieve what you want you will need to implement your own IAuthorizationFiler . 如果不满足这些条件中的任何一个,它将简单地返回return HttpUnauthorizedResult ,后者将响应代码设置为401。要实现所需的功能,您需要实现自己的IAuthorizationFiler 。
Your login page can check to see if the user is authenticated (HttpContext.User.Identity.IsAuthenticated), then redirect to a different page. 您的登录页面可以检查用户是否已通过身份验证(HttpContext.User.Identity.IsAuthenticated),然后重定向到其他页面。
Or alternatively, render differently for an authenticated user (hide the login form and instead display an appropriate message). 或者,为经过身份验证的用户进行不同的渲染(隐藏登录表单,而是显示适当的消息)。
You should check out Kazi Manzur Rashid's blog post on custom authorization providers: http://weblogs.asp.net/rashid/archive/2009/09/06/asp-net-mvc-and-authorization-and-monkey-patching.aspx . 您应该查看Kazi Manzur Rashid关于自定义授权提供程序的博客文章: http : //weblogs.asp.net/rashid/archive/2009/09/06/asp-net-mvc-and-authorization-and-monkey-patching。 aspx 。 It can be a pretty complex beast to do it properly. 正确地做到这一点可能是非常复杂的野兽。 So it comes down to a few options, 2 rather simple ways of doing it "wrong" and one rather complex way of doing it "right". 因此,归结为几种选择,两种是“错误”的相当简单的方法,一种是“正确”的相当复杂的方法。 Your call. 您的来电。 Either way - it's worth reading the blog post. 无论哪种方式-都值得阅读博客文章。
The way AuthorizeAttribute
is designed is that it will first look if the user is authenticated and then look if he is in role. 设计AuthorizeAttribute
的方式是,它首先将查看用户是否已通过身份验证,然后再查看用户是否具有角色。 If any of these conditions aren't satisfied it will simply return a HttpUnauthorizedResult
which in turn will set the response code to 401. 如果不满足这些条件中的任何一个,它将简单地返回HttpUnauthorizedResult
,该HttpUnauthorizedResult
会将响应代码设置为401。
To achieve what you want you will need to implement your own IAuthorizationFiler
. 为了实现您想要的,您将需要实现自己的IAuthorizationFiler
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.