using DG.Tool; using Microsoft.AspNetCore.Mvc; using System.ComponentModel.DataAnnotations; using System.Security.Cryptography; using System.Text; using System.Text.Json; namespace Cms.External.WebApi.Controllers { [ApiController] [Route("Api/[controller]")] [Produces("application/json")] public class BaseController : ControllerBase { protected void CheckSign(object? obj = null) { if (obj == null) { obj = new Dictionary(); } var bodyJson = JsonHelper.ToJson(obj); var appId = InitConfiguration.GetSection("SignConfig:AppId").Value; Dictionary res = new Dictionary(); var secret = InitConfiguration.GetSection("SignConfig:Secret").Value; if (string.IsNullOrWhiteSpace(appId) || string.IsNullOrWhiteSpace(secret)) { throw new Exception("appId或secret没有配置"); } var authorization = Request.Headers["authorization"].ToString(); var timestamps = Request.Headers["timestamps"].ToString(); var enStrList = new string[] { appId, bodyJson, secret, timestamps }; Array.Sort(enStrList, string.CompareOrdinal); //拼接 var enStr = string.Join("", enStrList); var md = _md5(enStr); if (authorization != $"{appId}:{md}") { throw new Exception("签名不合法"); } else { var nowTime = GetTimeStamp(); var diff = Convert.ToInt32(nowTime) - Convert.ToInt32(timestamps); if (diff > 1800) { throw new Exception("签名已过期"); } } } /// /// 计算 md5 /// /// /// private string _md5(string enCode) { string res = ""; byte[] data = Encoding.GetEncoding("utf-8").GetBytes(enCode); MD5 md5 = new MD5CryptoServiceProvider(); byte[] bytes = md5.ComputeHash(data); for (int i = 0; i < bytes.Length; i++) { res += bytes[i].ToString("x2"); } return res; } /// /// 获取时间戳 /// /// private string GetTimeStamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds).ToString(); } } }