.Net编写接口时,在对外接口上会加一个安全验证,保证接口的安全性。下面就是我在项目中所使用到的token验证:
创建ApiAuthorizeAttributes类 (类名自取) ,继承自
AuthorizeAttribute 基类,判断对方使用接口时,在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 类,如下:
public class GlobalAuthorizeAttributes: ApiAuthorizeAttributes
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new JsonNetResult(new AjaxResult { Success = false, Message = “没携带授权token或者token已过期!” });
}
}
这时在项目FilterConfig中配置过滤器,如下:

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