1. 程式人生 > >ASP.NET MVC使用AllowAnonymous特性跳過授權驗證

ASP.NET MVC使用AllowAnonymous特性跳過授權驗證

AllowAnonymous表示一個特性,該特性用於標記在授權期間要跳過 System.Web.Mvc.AuthorizeAttribute 的控制器和操作。

1、在Authorize過濾器類中新增如下程式碼

//判斷是否跳過授權過濾器
if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
    || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
{
    return;
}

完整程式碼:

using System.Web.Mvc;

namespace MvcApp.Filter
{
    /// <summary>
    /// 授權過濾器
    /// </summary>
    public class LoginAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //判斷是否跳過授權過濾器
            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
                || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                return;
            }

            //TODO:授權校驗
            
        }
    }
}

2、在要跳過授權校驗的控制器或Action上新增AllowAnonymous特性

[AllowAnonymous]
public class TestController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Index2()
    {
        return View();
    }
}

這樣上面TestController控制器下的所有Action都將跳過全域性的Authorize過濾器類。

或者新增在Action上:

[AllowAnonymous]
public ActionResult Index()
{
    return View();
}

這樣上面的Action將會跳過全域性的Authorize過濾器類。

其它方式:

通過判斷控制器名稱或Action的名稱來跳過Authorize過濾器類。

if (filterContext.ActionDescriptor.ControllerDescriptor.ControllerName == "控制器名稱" 
    || filterContext.ActionDescriptor.ActionName == "Action名稱")
{
    return;
}

例如:需要跳過TestController控制器下的所有Action。

public override void OnAuthorization(AuthorizationContext filterContext)
{

    if (filterContext.ActionDescriptor.ControllerDescriptor.ControllerName == "Test")
    {
        return;
    }

    //TODO:授權校驗
            
}