这里分享MVC的权限验证,内容中可能存在一些,莫名其妙的方法,那些是以前封装好的,大致可以根据方法名称知道他的意思。
using Game.Entity;
using Game.Entity.PlatformManager;
using Game.Facade;
using Game.Utils.Cache;
using Game.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace Game.Web.Authorize
{
/// <summary>
/// web mvc 管理员权限验证
/// </summary>
public class AdminLoginAuthorize : AuthorizeAttribute
{
/// <summary>
/// 管理员权限验证
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool result = false;
if (httpContext.User != null)
{
//获取用户票证
var ticObject = WHCache.Default.Get<CookiesCache>(FormsAuthentication.FormsCookieName);
if (ticObject != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(ticObject.ToString());
if (!ticket.Expired && ticket.CookiePath == httpContext.Request.UserHostAddress)
{
//获取Session缓存用户
var user = FacadeManage.aidePlatformManagerFacade.GetUserInfoFromCache();
if (user == null)
{
user = FacadeManage.aidePlatformManagerFacade.GetUserByUserID(int.Parse(ticket.Name.Split('_')[1]));
FacadeManage.aidePlatformManagerFacade.SaveUserCache(user);
}
//验证Session缓存用户是否和登录用户一致
if (ticket.Name == $"UserToken_{user.UserID}")
{
result = true;
}
}
}
}
return result;
}
/// <summary>
/// 处理授权失败的 HTTP 请求。
/// </summary>
/// <param name="filterContext">封装用于 System.Web.Mvc.AuthorizeAttribute 的信息。 filterContext 对象包括控制器、HTTP 上下文、请求上下文、操作结果和路由数据。</param>
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
string _errorMsg = "出错了";
if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
{
return;
}
//异步请求
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
ErrorType = this.GetType().Name,
Action = filterContext.ActionDescriptor.ActionName,
Message = _errorMsg
}
};
}
else
{
filterContext.Result = new RedirectResult("/Home/Login");
}
}
}
}