开发者

If current user isn't in role required by [Authorize], can I automatically redirect them?

开发者 https://www.devze.com 2023-01-04 06:57 出处:网络
In the ASP.NET MVC site I am building, I have some methods where the users who use them have to be in a certain role (as it happens, if they\'re not, it means that they\'re suspended from the site). T

In the ASP.NET MVC site I am building, I have some methods where the users who use them have to be in a certain role (as it happens, if they're not, it means that they're suspended from the site). To accomplish this, I'm using the [Authorize(Roles="RoleName")] attribute without any difficulties.

However, I don't quite understand what happens to users who don't pass that [Authorize] 开发者_如何学编程check? What are they shown?

I want to redirect suspended users to a different Action if they try to use these methods. For now, I've been using a blank [Authorize] attribute (without any roles specified) and then checking in the Action code whether the user is part of the Role or not.

My approach feels like a code smell to me. Is it possible to specify what to show to a user (or where to redirect them to) if they don't pass the [Authorize] check?


As stated on the AuthorizeAttribute MSDN page:

If an unauthorized user tries to access a method that is marked with the Authorize attribute, the MVC framework returns a 401 HTTP status code. If the site is configured to use ASP.NET forms authentication, the 401 status code causes the browser to redirect the user to the login page.

If you're using forms authentication and want to redirect to the login page, you have nothing to do. Otherwise implement your own IAuthorizationFilter to do the redirection.

Edit: see this blog post that basically reimplement the AuthorizeAttribute manually, with custom redirection.


If you don't want to implement your own IAuthorizationFilter I believe you should be able to override the default behavior of the Authorize attribute. Just inherit and override the HandleUnauthorizedRequest method. Granted you'll still need a way to determine if the user failed due to not being logged in vs not having the right permissions. It may be cleaner just to write your own authorization filter.

0

精彩评论

暂无评论...
验证码 换一张
取 消