MVC RoleProvider并授权属性 [英] MVC RoleProvider and Authorize attribute
问题描述
我已经实现了我自己的角色提供者,我不使用默认的。它的工作原理到如此地步,它可以告诉别人时,也不应是应该能够查看页面。
I have implemented my own role provider, and I'm not using the default one. It works to the point that it can tell when someone should or should not be able to view a page.
但是,它可以做到以下几点:
However, can it do the following:
- 如果用户没有登录,重定向到我的登录页面
- 如果一个用户登录,但没有正确的角色,重定向到一个不同的页面
我还没有想出如何与授权属性做到这一点,我只有:
I haven't figured out how to do this with the Authorize attribute, all I have is:
[Authorize(Roles="Admin")]
基本上我需要根据什么授权的一部分失败重定向到一个不同的页面。
Basically I need to redirect to a different page based on what part of the authorization fails.
我看着,看它是否有东西在web.config中,但没有明显的跳了出来。
I've looked to see if it were something in web.config but nothing obvious jumps out.
推荐答案
VoodooChild
回答#1。
有关#2 -
你可以做的是检查,如果用户登录在登录页面,并显示不同的消息或完全不同的页面(甚至做一个重定向到一个不同的动作)。
What you can do is check if the user is logged on the login page and display a different message or an entirely different page (or even do a redirect to a different action).
另外,您可以创建自己的授权属性。这将要求你在任何地方使用,而不是默认此属性 AuthorizeAttribute
Alternatively you can create your own authorization attribute. This will require that you use this attribute everywhere instead of the default AuthorizeAttribute
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "ActionName" },
{ "controller", "ControllerName" }
});
}
else
base.HandleUnauthorizedRequest(filterContext);
}
}
更新:
只要想到另一种方法。当一个重定向从不同的页面做了登录
页面,查询字符串 RETURNURL
也过去了。所以,你也可以检查,如果它包含的东西,用户通过验证,那么有可能在用户没有权限查看该页面。
Update:
Just thought of another method. When a redirect is done to login
page from a different page, a querystring ReturnUrl
is also passed. So you can also check if it contains something AND the user is authenticated, chances are the user didn't have permission to view that page.
这篇关于MVC RoleProvider并授权属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!