.Net EF Core接口登录验证

.Net编写接口时,在对外接口上会加一个安全验证,保证接口的安全性。下面就是我在项目中所使用到的token验证:

创建Api­Au­tho­rizeAt­trib­ut­es类 (类名自取) ,继承自
Autho­rizeAt­tribute 基类,判断对方使用接口时,在Headers 、Form或QueryString中是否带有token,如下:

        public  class ApiAuthorizeAttributes: AuthorizeAttribute
     {
         protected override bool AuthorizeCore(HttpContextBase httpContext)
         {
             base.AuthorizeCore(httpContext);
//查询Headers 或 Form 或QueryString(字符串)里有没有Token值   
        if (httpContext.Request.Headers.AllKeys.Count(t => t.ToLower() == "token") > 0 || httpContext.Request.Form.AllKeys.Count(t => t.ToLower() == "token") > 0 || httpContext.Request.QueryString.AllKeys.Count(t => t.ToLower() == "token") > 0)
        {
            //如果有则获取
            string token = httpContext.Request.Headers["token"];
            if (string.IsNullOrEmpty(token))
                token = httpContext.Request.Form["token"];
            if (string.IsNullOrEmpty(token))
                token = httpContext.Request.QueryString["token"];
            if (HttpRuntime.Cache["token"] != null)
            {
                //使用接口时在查询Headers里把token带过去
                return HttpRuntime.Cache["token"] is Dictionary<string, object> dictionary && dictionary.ContainsKey(token);  //把获取的Token值跟Dictionary对比
            }
        }

        return false;
    }
}

若带有把通过验证,同时token值放入缓存,以便使用。若无token则返回false,验证不通过。

同时新建类GlobalAuthorizeAttributes(类名自取),继承上面新建的ApiAuthorizeAttributes 类,如下:

pub­lic class Glob­al­Au­tho­rizeAt­trib­ut­es: Api­Au­tho­rizeAt­trib­ut­es
{
pro­tect­ed over­ride void HandleUnauthorizedRequest(AuthorizationContext fil­ter­Con­text)
{
filterContext.Result = new JsonNetResult(new AjaxRe­sult { Suc­cess = false, Mes­sage = “没携带授权­to­ken或者­to­ken已过期!” });
}
}

这时在项目FilterConfig中配置过滤器,如下:

配置介绍

到了这里,接口的登录验证就做完了。

为您推荐

发表评论

您的电子邮箱地址不会被公开。