最近的一个项目要求服务端与UI层分离,业务层以WebApi方式向外提供所有业务服务,服务在数据保密性方面提出了要求,主要包括:
1:客户端认证;
2:服务请求超时(默认5分钟);
3:服务Get请求的参数密文传输。
以上三个需求为一般的网络服务比较常见的简单要求,在WebApi项目中也比较容易实现,以下是我采用的两种实现方式(任意一种即可):
一:继承HttpClient来加入数据(Uri)加密,加入验证Header,继承ApiController来对Header进行合法性验证,并解密Uri
客户端的关键代码包括对HttpClient继承实现:
public class MyHttpClient : HttpClient { private static MyHttpClient _myClient; public static MyHttpClient Instance { get { if(_myClient!=null)return _myClient; _myClient = new MyHttpClient(); _myClient.DefaultRequestHeaders.Add("Mac", MacMd5); return _myClient; } } private MyHttpClient() { } private static readonly IAuthorize _authorize = new MacAuthorize(); private static string _macMd5 = string.Empty; private static string MacMd5 { get { if (!string.IsNullOrEmpty(_macMd5)) return _macMd5; var macAddress = _authorize.UniqueId; if (string.IsNullOrEmpty(macAddress)) return string.Empty; _macMd5 = macAddress.GetMD5(); return _macMd5; } } private static string TimeAes { get { var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); var aesTime = time.AesEncrypt(); return aesTime; } } private static void AddHeader(ref string url) { var segs = url.Split('/'); ]; if (para.Contains("=")) { var aes = para.AesEncrypt(); url = url.Replace(para, aes.GetMD5()); IEnumerable<string> p = new List<string>(); if (_myClient.DefaultRequestHeaders.TryGetValues("Param", out p)) _myClient.DefaultRequestHeaders.Remove("Param"); _myClient.DefaultRequestHeaders.Add("Param",aes); } IEnumerable<string> time = new List<string>(); if (_myClient.DefaultRequestHeaders.TryGetValues("Time", out time)) _myClient.DefaultRequestHeaders.Remove("Time"); _myClient.DefaultRequestHeaders.Add("Time", TimeAes); } public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var url = request.RequestUri.AbsoluteUri; AddHeader(ref url); return base.SendAsync(request, cancellationToken); } public override int GetHashCode() { return _myClient.GetHashCode(); } }
其中时间戳为了简便,未转为ms格式进行验证,仅作为字符串进行了验证。
在客户端进行调用时,通过继承的MyHttpClient发送服务请求即可:
var client = MyHttpClient.Instance; var response = client.GetAsync(urlBase.AbsoluteUri + "api/test/GetUser/id=123123&name=jiakai").Result;
服务端的关键代码包括对ApiController的继承实现:
public class BaseApiController : ApiController { protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); //获取请求头信息 var requestHeader = controllerContext.Request.Headers; IEnumerable<string> mac = new List<string>(); requestHeader.TryGetValues("Mac", out mac); IEnumerable<string> time = new List<string>(); requestHeader.TryGetValues("Time", out time); IEnumerable<string> para = new List<string>(); requestHeader.TryGetValues("Param", out para); var paramList = controllerContext.Request.RequestUri.AbsoluteUri.Split('/'); if (mac == null || time == null || para == null) { var resp = Request.CreateResponse<string>(HttpStatusCode.Forbidden, "非法请求", "application/json"); throw new HttpResponseException(resp); } //验证机器MAC地址 if (mac.Any()&&!string.IsNullOrEmpty(mac.First())) { //TODO:验证机器MAC地址是否为已注册MAC地址 } //验证时间戳 if (time.Any() && !string.IsNullOrEmpty(time.First())) { var t = Convert.ToDateTime(time.First().AesDecrypt()); ) < DateTime.Now) { var resp = Request.CreateResponse<string>(HttpStatusCode.RequestTimeout, "请求过期", "application/json"); throw new HttpResponseException(resp); } } //验证参数MD5 if (para.Any() && !string.IsNullOrEmpty(para.First())) { ]; if (para.First().GetMD5() != newMd5) { var resp = Request.CreateResponse<string>(HttpStatusCode.Forbidden, "参数MD5验证失败", "application/json"); throw new HttpResponseException(resp); } } } }
同样,在业务实现的Controller中,继承改为BaseApiController即可:
public class TestController : BaseApiController { //TODO:业务服务具体实现 }
二:通过对WebApi消息处理框架中HttpMessageHandler的自定义实现,并分别注入到Request及Response的消息处理阶段,来实现加密/解密的功能
客户端HttpClient中HttpMessageHandler的实现:
public class RequestHandler : DelegatingHandler { private static string TimeAes { get { var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); var aesTime = time.AesEncrypt(); return aesTime; } } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var uri = request.RequestUri.AbsoluteUri; var port = request.RequestUri.Port; var para = uri.Split('/').Last(); if (para.Contains("=")) { var aes = para.AesEncrypt(); uri = uri.Replace(para, aes.GetMD5()); IEnumerable<string> p = new List<string>(); if (request.Headers.TryGetValues("Param", out p)) request.Headers.Remove("Param"); request.Headers.Add("Param", aes); } IEnumerable<string> time = new List<string>(); if (request.Headers.TryGetValues("Time", out time)) request.Headers.Remove("Time"); request.Headers.Add("Time", TimeAes); request.RequestUri = new Uri(uri); return base.SendAsync(request, cancellationToken); } }
在实现了自定义的HttpMessageHandler后,实现一个HttpClient工厂,对外提供一个注入了该HttpMessageHandler的HttpClient单例对象:
public class AtmHttpClientFactory { private static HttpClient _atmClient; private readonly static HttpClientHandler ClientHandler = new HttpClientHandler(); public static HttpClient GetClient() { if (_atmClient != null) return _atmClient; _atmClient = new HttpClient(new RequestHandler() {InnerHandler = ClientHandler }); _atmClient.DefaultRequestHeaders.Add("Mac", MacMd5); return _atmClient; } private AtmHttpClientFactory() { } private static readonly IAuthorize _authorize = new MacAuthorize(); private static string _macMd5 = String.Empty; private static string MacMd5 { get { if (!String.IsNullOrEmpty(_macMd5)) return _macMd5; var macAddress = _authorize.UniqueId; if (String.IsNullOrEmpty(macAddress)) return String.Empty; _macMd5 = macAddress.GetMD5(); return _macMd5; } } }
这样,在客户端的调用加密过程就完全被封装,简化为如下:
//调用实现1 var myClient = AtmHttpClientFactory.GetClient(); var myResponse = myClient.GetAsync("http://api.ezbatm.com:7777/api/test/GetUser/id=123123&name=jiakai").Result;
服务端也是类似的方法,在app的config中注入我们自己实现的服务端HttpMessageHandler即可。response的HttpMessageHandler实现:
public class ResponseHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { //获取请求头信息 IEnumerable<string> mac = new List<string>(); request.Headers.TryGetValues("Mac", out mac); IEnumerable<string> time = new List<string>(); request.Headers.TryGetValues("Time", out time); IEnumerable<string> para = new List<string>(); request.Headers.TryGetValues("Param", out para); var paramList = request.RequestUri.AbsoluteUri.Split('/'); //验证Header是否完整 if (mac == null || time == null || para == null) { return RequestNotAcceptable(); } //验证机器MAC地址 if (mac.Any() && !string.IsNullOrEmpty(mac.First())) { //TODO:验证机器MAC地址是否为已注册MAC地址 } //验证时间戳 if (time.Any() && !string.IsNullOrEmpty(time.First())) { var t = Convert.ToDateTime(time.First().AesDecrypt()); ) < DateTime.Now) { return RequestTimeOut(); } } //验证参数MD5 if (para.Any() && !string.IsNullOrEmpty(para.First())) { ]; //if (para.First().GetMD5() != newMd5) { return RequestForbidden(); } } return base.SendAsync(request, cancellationToken); } private static Task<HttpResponseMessage> RequestForbidden() { return Task.Factory.StartNew(() => { return new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent("请求未通过认证") }; }); } private static Task<HttpResponseMessage> RequestTimeOut() { return Task.Factory.StartNew(() => { return new HttpResponseMessage(HttpStatusCode.RequestTimeout) { Content = new StringContent("请求已超时") }; }); } private static Task<HttpResponseMessage> RequestNotAcceptable() { return Task.Factory.StartNew(() => { return new HttpResponseMessage(HttpStatusCode.NotAcceptable) { Content = new StringContent("请求为非法请求") }; }); } }
之后,在(owin框架)Startup中注入该自定义HttpMessageHandler即可:
public void Configuration(IAppBuilder app) { // Configure Web API for self-host. var config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{param}", defaults: new { id = RouteParameter.Optional } ); //注入response handler config.MessageHandlers.Add(new ResponseHandler()); app.UseWebApi(config); }
完成了以上客户端+服务器端的工作后,即可按照我们的实际需求对Request及Response消息进行自定义的处理。
总结:以上两种方法中,客户端及服务器端的方案都是解耦的,也就是是,你可以采用方法一的客户端方案+方法二的服务器端方案,等等以此类推。