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": break;//只是为了同时显示restful四种方式才有这部分无意义代码 //实际该以哪种方式进行请求应遵循restful标准 case "POST": case "PUT": case "DELETE": 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 { }
时间: 2024-10-29 04:25:02