asp.net-mvc 仅当不使用角色时,如何将 [Authorize] 重定向到 loginUrl?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2504923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to redirect [Authorize] to loginUrl only when Roles are not used?
提问by royco
I'd like [Authorize]to redirect to loginUrlunless I'm also using a role, such as [Authorize (Roles="Admin")]. In that case, I want to simply display a page saying the user isn't authorized.
我想[Authorize]重定向到loginUrl除非我还使用了一个角色,例如[Authorize (Roles="Admin")]. 在这种情况下,我只想显示一个页面,说明用户未经授权。
What should I do?
我该怎么办?
回答by Robert Harvey
Here is the code from my modified implementation of AuthorizeAttribute; I named it SecurityAttribute. The only thing that I have changed is the OnAuthorizationmethod, and I added an additional string property for the Url to redirect to an Unauthorized page:
这是我修改后的实现中的代码AuthorizeAttribute;我给它起了名字SecurityAttribute。我唯一改变的是OnAuthorization方法,我为 Url 添加了一个额外的字符串属性以重定向到一个未经授权的页面:
// Set default Unauthorized Page Url here
private string _notifyUrl = "/Error/Unauthorized";
public string NotifyUrl {
get { return _notifyUrl; } set { _notifyUrl = value; }
}
public override void OnAuthorization(AuthorizationContext filterContext) {
if (filterContext == null) {
throw new ArgumentNullException("filterContext");
}
if (AuthorizeCore(filterContext.HttpContext)) {
HttpCachePolicyBase cachePolicy =
filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge(new TimeSpan(0));
cachePolicy.AddValidationCallback(CacheValidateHandler, null);
}
/// This code added to support custom Unauthorized pages.
else if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
if (NotifyUrl != null)
filterContext.Result = new RedirectResult(NotifyUrl);
else
// Redirect to Login page.
HandleUnauthorizedRequest(filterContext);
}
/// End of additional code
else
{
// Redirect to Login page.
HandleUnauthorizedRequest(filterContext);
}
}
You call it the same way as the original AuthorizeAttribute, except that there is an additional property to override the Unauthorized Page Url:
您可以按照与原始 相同的方式调用它AuthorizeAttribute,除了有一个额外的属性来覆盖未经授权的页面 URL:
// Use custom Unauthorized page:
[Security (Roles="Admin, User", NotifyUrl="/UnauthorizedPage")]
// Use default Unauthorized page:
[Security (Roles="Admin, User")]
回答by codingbiz
Extend the AuthorizeAttributeclass and override HandleUnauthorizedRequest
扩展AuthorizeAttribute类并覆盖HandleUnauthorizedRequest
public class RoleAuthorizeAttribute : AuthorizeAttribute
{
private string redirectUrl = "";
public RoleAuthorizeAttribute() : base()
{
}
public RoleAuthorizeAttribute(string redirectUrl) : base()
{
this.redirectUrl = redirectUrl;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
string authUrl = this.redirectUrl; //passed from attribute
//if null, get it from config
if (String.IsNullOrEmpty(authUrl))
authUrl = System.Web.Configuration.WebConfigurationManager.AppSettings["RolesAuthRedirectUrl"];
if (!String.IsNullOrEmpty(authUrl))
filterContext.HttpContext.Response.Redirect(authUrl);
}
//else do normal process
base.HandleUnauthorizedRequest(filterContext);
}
}
Usage
用法
[RoleAuthorize(Roles = "Admin, Editor")]
public class AccountController : Controller
{
}
And make sure you add your AppSettings entry in the config
并确保在配置中添加您的 AppSettings 条目
<appSettings>
<add key="RolesAuthRedirectUrl" value="http://mysite/myauthorizedpage" />
</appSettings>
回答by tvanfosson
The easiest way I've found is to extend and customize the AuthorizeAttribute so that it does something different (i.e., not set an HttpUnauthorizedResult) when the Role check fails. I've written an articleabout this on my blog that you might find useful. The article describes much what you are wanting, though it goes further and allows the user who "owns" the data to also have access to the action. I think it should be fairly easy to modify for your purposes -- you'd just need to remove the "or owner" part.
我发现的最简单的方法是扩展和自定义 AuthorizeAttribute 以便它在角色检查失败时执行不同的操作(即,不设置 HttpUnauthorizedResult)。我在我的博客上写了一篇关于这个的文章,你可能会觉得有用。这篇文章描述了您想要什么,尽管它更进一步,并允许“拥有”数据的用户也可以访问该操作。我认为根据您的目的进行修改应该相当容易——您只需要删除“或所有者”部分。

