如何重定向仅当不使用角色[授权]至loginUrl? [英] How to redirect [Authorize] to loginUrl only when Roles are not used?

查看:139
本文介绍了如何重定向仅当不使用角色[授权]至loginUrl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想 [授权] 来重定向到的 loginUrl 的,除非我还使用了作用,如 [授权(角色=管理员)] 。在这种情况下,我想简单地显示一个页面称未授权用户。

I'd like [Authorize] to redirect to loginUrl unless 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.

我应该怎么办?

推荐答案

下面是从我修改实施 AuthorizeAttribute 的code;我把它命名为 SecurityAttribute 。我所唯一改变的是 OnAuthorization 法,我增加了一个额外的字符串属性的URL重定向到一个未经授权的网页:

Here is the code from my modified implementation of AuthorizeAttribute; I named it SecurityAttribute. The only thing that I have changed is the OnAuthorization method, and I added an additional string property for the Url to redirect to an Unauthorized page:

// 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);
    }
}

您拨打的方式为同一原始 AuthorizeAttribute ,但有一个额外的属性覆盖未经授权的网页网址:

You call it the same way as the original AuthorizeAttribute, except that there is an additional property to override the Unauthorized Page Url:

// Use custom Unauthorized page:
[Security (Roles="Admin, User", NotifyUrl="/UnauthorizedPage")]

// Use default Unauthorized page:
[Security (Roles="Admin, User")]

这篇关于如何重定向仅当不使用角色[授权]至loginUrl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆