本文实例环境及版本.NetCore3.1
实现系统登录验证方式个人总结如下:
1、自定义行为过滤器
2、自定义身份验证过滤器
3、新建BaseController在OnActionExecuting中实现
一、自定义行为过滤器在OnActionExecuting中实现
1、新建SystemAuthorizeFilter过滤器继承自 IActionFilter
/// <summary>
/// 自定义行为过滤器,实现登录及权限的验证
/// </summary>
public class SystemAuthorizeFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
//throw new NotImplementedException();
}
/// <summary>
/// 在执行控制器中的Action方法之前执行该方法 判断当前用户是否登录
/// </summary>
/// <param name="context"></param>
public void OnActionExecuting(ActionExecutingContext context)
{ //排除可以匿名访问的 未登录时
if (HasAllow(context) == false && context.HttpContext.Session.GetString("User") == null)
{
bool isAjax = IsAjax(context.HttpContext.Request);
//如果是Ajax请求自定义返回json
if (isAjax)
{
context.Result = new JsonResult(new { Code = 401, Msg = "登录已失效,请重新登录2!" }) {
StatusCode=StatusCodes.Status401Unauthorized
};
}
else
{
ContentResult Content = new ContentResult();
Content.Content = "<script type='text/javascript'>alert('登录已失效,请重新登录!'); top.location.href='/Login/Login';</script>";
Content.ContentType = "text/html;charset=utf-8";
context.Result = Content;
}
}
}
/// <summary>
/// 排除掉控制器不需要鉴权 即加[AllowAnonymous]特性的无需鉴权
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static bool HasAllow(ActionExecutingContext context)
{
var filters = context.Filters;
if (filters.OfType<IAllowAnonymousFilter>().Any())
{
return true;
}
var endpoint = context.HttpContext.GetEndpoint();
return endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null;
}
/// <summary>
/// 判断是否是Ajax请求
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public static bool IsAjax(HttpRequest req)
{
bool result = false;
var xreq = req.Headers.ContainsKey("x-requested-with");
if (xreq)
{
result = req.Headers["x-requested-with"] == "XMLHttpRequest";
}
return result;
}
}
2、在Startup的ConfigureServices中添加
//配置系统过滤器
services.AddControllersWithViews().AddMvcOptions(options =>
{
//自定义行为过滤器的方式,验证是否登录及用户权限
options.Filters.Add<SystemAuthorizeFilter>();
}).AddNewtonsoftJson(options=> {
//全局日期格式化
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
//返回的Json大小写原样输出
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
3、在登录控制器如:LoginController.cs 或不需要鉴权的控制器或方法上添加[AllowAnonymous] 特性即可。
4、在页面上Ajax请求中加入判断如果返回的为401时给予提示并跳转至登录页面
$.ajax({
type: "POST",
data: "",
async: false,
dataType: "json",
url: "",
beforeSend: function () {
},
success: function (data) {
if (data.Code != null && data.Code != "undefined" && data.Code == 401) { alert('登录已失效,请重新登录!'); top.location.href='/Login/Login'; } console.log(data); }, complete: function () { }, error: function (data) { } });
二、自定义身份验证过滤器
新建CustomAuthorizeFilter过滤器继承自 IAuthorizationFilter
/// <summary>
/// 自定义身份验证过滤器,实现登录及权限的验证
/// </summary>
public class CustomAuthorizeFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
//如果需要授权 但未登录
if (HasAllowAnonymous(context) == false && context.HttpContext.Session.GetString("User") == null)
{
bool isAjax = IsAjax(context.HttpContext.Request);
//如果是Ajax请求自定义返回json
if (isAjax)
{
context.Result = new JsonResult(new { Code = 401, Msg = "登录已失效,请重新登录2!" })
{
StatusCode = StatusCodes.Status401Unauthorized
};
}
else
{
ContentResult Content = new ContentResult();
Content.Content = "<script type='text/javascript'> alert('登录已失效,请重新登录!'); top.location.href='/Login/Login'; </script>";
Content.ContentType = "text/html;charset=utf-8";
context.Result = Content;
}
}
}
/// <summary>
/// 排除掉控制器不需要鉴权的
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private static bool HasAllowAnonymous(AuthorizationFilterContext context)
{
var filters = context.Filters;
if (filters.OfType<IAllowAnonymousFilter>().Any())
{
return true;
}
var endpoint = context.HttpContext.GetEndpoint();
return endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null;
}
/// <summary>
/// 判断是否是Ajax请求
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public static bool IsAjax(HttpRequest req)
{
bool result = false;
var xreq = req.Headers.ContainsKey("x-requested-with");
if (xreq)
{
result = req.Headers["x-requested-with"] == "XMLHttpRequest";
}
return result;
}
}
使用方式同上,不需要鉴权的控制器或方法上添加[AllowAnonymous] 特性即可。
三、新建BaseController在OnActionExecuting中实现
在BaseController中重写OnActionExecuting方法
/// <summary>
/// 在执行控制器中的Action方法之前执行该方法 判断当前用户是否登录
/// </summary>
/// <param name="context"></param>
public override void OnActionExecuting(ActionExecutingContext context)
{
if (context.HttpContext.Session.GetString("User")==null)
{
//context.Result = Redirect("/Login/Login");
ContentResult Content = new ContentResult();
Content.Content= "<script type='text/javascript'>alert('登录已失效,请重新登录!');top.location.href='/Login/Login'</script>";
Content.ContentType = "text/html;charset=utf-8";
context.Result = Content;
return;
}
}
其他的修改可参考上面两种做补充,在需要鉴权的控制器上集成该BaseController即可。
到此这篇关于.NetCore使用过滤器实现登录权限认证几种方式总结的文章就介绍到这了,更多相关.NetCore登录权限认证内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!