using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Site.Filters
{
public enum AuthorizeScheme
{
Backend = 0,
Frontend = 1
}
// 自定义用户认证过滤器
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class CustomAuthorization : AuthorizeAttribute // Authorize [ˈɔ:θəraɪz] vt. 授权,批准,委托
{
public AuthorizeScheme Scheme { get; set; }
public CustomAuthorization() : base()
{
Scheme = AuthorizeScheme.Frontend;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
//解决自定义AuthorizeAttribute实现授权管理,AllowAnonymous属性失效导致无法匿名访问控制器的问题
bool flag = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
if (flag)
{
return;
}
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
string returnUrl = filterContext.RequestContext.HttpContext.Request.Url.ToString();
string host = HttpContext.Current.Request.Url.Host;
int port = HttpContext.Current.Request.Url.Port;
if (Scheme == AuthorizeScheme.Frontend)
{
filterContext.HttpContext.Response.Redirect($"http://{host}:{port}/Login?return_url={returnUrl}");
}
else if (Scheme == AuthorizeScheme.Backend)
{
filterContext.HttpContext.Response.Redirect($"http://{host}:{port}/Admin/Home/Login?return_url={returnUrl}");
}
}
base.OnAuthorization(filterContext);
}
}
}
本文为“技术点滴”的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。