ASP.NET MVC中利用AuthorizeAttribute实现访问身份是否合法以及Cookie过期问题的处理

时间:2023-03-09 00:21:32
ASP.NET MVC中利用AuthorizeAttribute实现访问身份是否合法以及Cookie过期问题的处理

话说来到上海已经快半年了,时光如白驹过隙,稍微不注意,时间就溜走了,倒是没有那么忙碌,闲暇之际来博客园还是比较多的,记得上次在逛博问的时候看到有同志在问MVC中Cookie过期后如何作相关处理,他在阐述那么多页面不可能都去一个个手动处理。其实MVC很牛逼的地方就是把Attribute利用的非常完美,接下来就来看下它是如何做到的吧!

第一步、我们要定义一个登录过滤标签-LoginFilterAttribute并且继承AuthorizeAttribute。来看下它内部是啥样子

 // Summary:
// Represents an attribute that is used to restrict access by callers to an
// action method.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
// Summary:
// Initializes a new instance of the System.Web.Mvc.AuthorizeAttribute class.
public AuthorizeAttribute(); // Summary:
// Gets or sets the user roles.
//
// Returns:
// The user roles.
public string Roles { get; set; }
//
// Summary:
// Gets the unique identifier for this attribute.
//
// Returns:
// The unique identifier for this attribute.
public override object TypeId { get; }
//
// Summary:
// Gets or sets the authorized users.
//
// Returns:
// The authorized users.
public string Users { get; set; } // Summary:
// When overridden, provides an entry point for custom authorization checks.
//
// Parameters:
// httpContext:
// The HTTP context, which encapsulates all HTTP-specific information about
// an individual HTTP request.
//
// Returns:
// true if the user is authorized; otherwise, false.
//
// Exceptions:
// System.ArgumentNullException:
// The httpContext parameter is null.
protected virtual bool AuthorizeCore(HttpContextBase httpContext);
//
// Summary:
// Processes HTTP requests that fail authorization.
//
// Parameters:
// filterContext:
// Encapsulates the information for using System.Web.Mvc.AuthorizeAttribute.
// The filterContext object contains the controller, HTTP context, request context,
// action result, and route data.
protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
//
// Summary:
// Called when a process requests authorization.
//
// Parameters:
// filterContext:
// The filter context, which encapsulates information for using System.Web.Mvc.AuthorizeAttribute.
//
// Exceptions:
// System.ArgumentNullException:
// The filterContext parameter is null.
public virtual void OnAuthorization(AuthorizationContext filterContext);
//
// Summary:
// Called when the caching module requests authorization.
//
// Parameters:
// httpContext:
// The HTTP context, which encapsulates all HTTP-specific information about
// an individual HTTP request.
//
// Returns:
// A reference to the validation status.
//
// Exceptions:
// System.ArgumentNullException:
// The httpContext parameter is null.
protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
}

这里我们要重写OnAuthorization这个方法。

接下来就看下LoginFilterAttibute这个"儿子"是怎么完成"老子"交待的任务了。直接上code

 public class LoginFilterAttribute:AuthorizeAttribute
{ private static string formsCookieName = FormsAuthentication.FormsCookieName; public override void OnAuthorization(AuthorizationContext filterContext)
{
HttpCookie formsCookie =
System.Web.CookieManager.GetCookie(formsCookieName);
if (formsCookie == null)
{
//页面Cookie过期后返回登录页面
RedirectToLoginPage(filterContext);
return;
} bool autenticated = HttpContext.Current.User.Identity.IsAuthenticated; //一旦发现身份不合法就作相应的处理.
if (!autenticated )
{
//redirect to login
RedirectToLoginPage(filterContext);
return;
}
//if success add login data to context
}
private static void RedirectToLoginPage(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new JsonResult()
{
Data = new {
status = "error",
message = "Unauthorized_Message"
},
JsonRequestBehavior= JsonRequestBehavior.AllowGet
};
return;
}
else
{
//返回登录页面的相关处理..........
}
}

第二步、新建一个基类Controller-BaseController并且继承Controller。

     [LoginFilter]//此处就是我们上面定义的LoginFilterAttribute
public abstract partial class BaseController : Controller
{
public BaseController(){ }
//........其他相关处理
}

第三步、不是有很多页面吗?那我只要在对应的Controller去继承那个BaseController就实现了,在访问任何一个页面都会去作相应的过滤和处理。

 Public Class LoginController:BaseController
{
Public ActionResult Index()
{
//........
return View();
}
}

以上纯属个人观点,如有雷同纯属巧合!谢谢阅读,如果对您有帮助,请点关注并推荐!