开发者

Question about [Authorize] Attribute for Administrators

开发者 https://www.devze.com 2023-02-28 06:56 出处:网络
If i have an Area in my ASP.NET MVC 3 (Razor) Web application, where all controllers derive from a base controller that looks like this:

If i have an Area in my ASP.NET MVC 3 (Razor) Web application, where all controllers derive from a base controller that looks like this:

[Authorize(Roles="Administrator")]
public class AdminController : Controller
{

}

When a non-administrator tries to access a URL in that area, they get redirected to the login page specified in the web.config.

But this doesn't really make开发者_如何学C sense if the user is already authenticated, but not an administrator. In that scenario, shouldn't we be returned a HTTP 401?

My question is basically how do people handle this - do they create custom authorize attributes?


See this thread ... ASP.Net converts 401 to 302 error codes

What you really want to do is return a 403 code. 401 is intended for authentication challenges. ASP.NET forms authorization intercepts 401 and pushes users to the login page.

If you still want to do a 401, could you describe what is the expected experience for the end user?


I work with ASP.NET MVC4 Beta and today I noticed that if I add ReturnUrl parameter to querystring, the forms module doesn't change the response.

So if action i/Rate has attribute [Authorize] then

<a href="/xm/i/Rate?pid=3&amp;count=2&amp;ReturnUrl=%2F">..</a>

returns 401. I don't know if it is bug, or feature, but now it works as described.


we have custom authorize filter attribute for such scenarios and we take user to custom error page

public void OnAuthorization(AuthorizationContext filterContext) {


if(//user does not have permission){

filterContext.Result = new RedirectResult("/Error/AccessDenied");

}


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.

Refrence:http://msdn.microsoft.com/zh-tw/library/system.web.mvc.authorizeattribute.aspx

Other similar question: How to intercept 401 from Forms Authentication in ASP.NET MVC?

0

精彩评论

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