1 public class ActionFilter : ActionFilterAttribute 2 { 3 public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) 4 { 5 base.OnActionExecuting(actionContext); 6 //获取请求消息提数据 7 Stream stream = actionContext.Request.Content.ReadAsStreamAsync().Result; 8 Encoding encoding = Encoding.UTF8; 9 stream.Position = 0; 10 string responseData = ""; 11 using (StreamReader reader = new StreamReader(stream, encoding)) 12 { 13 responseData = reader.ReadToEnd().ToString(); 14 } 15 //反序列化进行处理 16 var serialize = new JavaScriptSerializer(); 17 var obj = serialize.Deserialize<RequestDTO>(responseData); 18 //在action执行前终止请求时,应该使用填充方法Response,将不返回action方法体。 19 if (obj == null) 20 actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, obj); 21 22 if (string.IsNullOrEmpty(obj.PhoneType) || string.IsNullOrEmpty(obj.PhoneVersion) 23 || string.IsNullOrEmpty(obj.PhoneID) || obj.StartCity < 1) 24 { 25 actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, obj); 26 } 27 } 28 }
WebAPI 用户认证防篡改实现HMAC(二)签名验证 AbsBaseAuthenticationAttribute
分类:
版权声明:本文为starfd原创文章,未经博主允许不得转载。
WebAPI的用户身份认证与MVC一样都是通过Attribute进行验证,此处定义了一个抽象基类,子类需要实现根据合作号获取合作用户信息的抽象方法
AbsBaseAuthenticationAttribute
using System; using System.Web; using System.Collections.Specialized; using System.Net; using System.Net.Http; using System.Text.RegularExpressions; using System.Web.Http.Controllers; using System.Web.Http.Filters; /// <summary> /// WebAPI防篡改签名验证抽象基类Attribute /// </summary> public abstract class AbsBaseAuthenticationAttribute : ActionFilterAttribute { /// <summary> /// Occurs before the action method is invoked. /// </summary> /// <param name="actionContext">The action context</param> public override void OnActionExecuting(HttpActionContext actionContext) { //获取Asp.Net对应的Request var request = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request; NameValueCollection getCollection = request.QueryString;//此签名要求Partner及Sign均通过QueryString传递 if (getCollection != null && getCollection.Count > 0) { string partner = getCollection[SecuritySignHelper.Partner]; string sign = getCollection[SecuritySignHelper.Sign]; if (!string.IsNullOrWhiteSpace(partner)//必须包含partner && !string.IsNullOrWhiteSpace(sign)//必须包含sign && Regex.IsMatch(sign, "^[0-9A-Za-z]{32}$"))//sign必须为32位Md5摘要 { //获取partner对应的key //这里暂时只做了合作key校验,不做访问权限校验,如有需要,此处可进行调整,建议RBAC string partnerKey = this.GetPartnerKey(partner); if (!string.IsNullOrWhiteSpace(partnerKey)) { NameValueCollection postCollection = null; switch (request.RequestType.ToUpper()) { case "GET": case "DELETE": break;//只是为了同时显示restful四种方式才有这部分无意义代码 //实际该以哪种方式进行请求应遵循restful标准 case "POST": case "PUT": postCollection = request.Form;//post的数据必须通过application/x-www-form-urlencoded方式传递 break; default: throw new NotImplementedException(); } //根据请求数据获取MD5签名 string vSign = getCollection.GetSecuritySign(partner, partnerKey, postCollection); if (string.Equals(sign, vSign, StringComparison.OrdinalIgnoreCase)) {//验证通过,执行基类方法 base.OnActionExecuting(actionContext); return; } } } } //此处暂时以401返回,可调整为其它返回 actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); //actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); } /// <summary> /// 获取合作号对应的合作Key,如果未能获取,则返回空字符串或者null /// </summary> /// <param name="partner"></param> /// <returns></returns> protected abstract string GetPartnerKey(string partner); }
子类例子
public class AuthenticationAttribute : AbsBaseAuthenticationAttribute { protected override string GetPartnerKey(string partner) { //TODO:从缓存中或者其它地方读取数据 return "bbb"; } }实际可以在需要身份验证的ApiController上增加[Authentication],也可以写一个基类,然后需要身份验证的ApiController继承自该基类
[Authentication] public class ApiControllerBase : ApiController { }
当然如果项目中所有的api都需要进行签名访问,那么直接可以进行注册,就不需要上面的ApiControllerBase了
config.Filters.Add(new AuthenticationAttribute());