简体   繁体   中英

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? 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. 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 .

Your login page can check to see if the user is authenticated (HttpContext.User.Identity.IsAuthenticated), then redirect to a different page.

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 . 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. If any of these conditions aren't satisfied it will simply 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM