(精華)2020年6月29日 C#類庫 介面簽名校驗

愚公搬程式碼發表於2020-06-29
using Coldairarrow.Business.Base_Manage;
using Coldairarrow.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace Core.Api
{
    /*
        ==== 簽名校驗 ====
        為保證介面安全,每次請求必帶以下header
        | header名 | 型別 | 描述 |
        | appId | string | 應用Id |
        | time | string | 當前時間,格式為:2020-06-29 23:00:00 |
        | guid | string | GUID字串,作為請求唯一標誌,防止重複請求 |
        | sign| string | 簽名,簽名演算法如下 |
        簽名演算法示例:
        令:
        appId=xxx
        appSecret=xxx
        time=2017-01-01 23:00:00
        guid=d0595245-60db-495d-9c0e-fea931b8d69a
        請求的body={"aaa":"aaa"}
        1: 依次拼接appId+time+guid+body+appSecret得到xxx2017-01-01 23:00:00d0595245-60db-495d-9c0e-fea931b8d69a{"aaa":"aaa"}xxx
        2: 將上面拼接字串進行MD5(32位)即可得到簽名
        sign=MD5(xxx2017-01-01 23:00:00d0595245-60db-495d-9c0e-fea931b8d69a{"aaa":"aaa"}xxx)
            =4e30f1eca521485c208f642a7d927ff0
        3: 在header中攜帶上述的appId、time、guid、sign即可
    */
    /// <summary>
    /// 校驗簽名、十分嚴格
    /// 防抵賴、防偽造、防重複呼叫
    /// </summary>
    public class CheckSignAttribute : BaseActionFilterAsync
    {
        /// <summary>
        /// Action執行之前執行
        /// </summary>
        /// <param name="filterContext"></param>
        public async override Task OnActionExecuting(ActionExecutingContext filterContext)
        {
            //判斷是否需要簽名
            if (filterContext.ContainsFilter<IgnoreSignAttribute>())
                return;
            var request = filterContext.HttpContext.Request;
            IServiceProvider serviceProvider = filterContext.HttpContext.RequestServices;
            IBase_AppSecretBusiness appSecretBus = serviceProvider.GetService<IBase_AppSecretBusiness>();
            ILogger logger = serviceProvider.GetService<ILogger<CheckSignAttribute>>();
            var cache = serviceProvider.GetService<IDistributedCache>();

            string appId = request.Headers["appId"].ToString();
            if (appId.IsNullOrEmpty())
            {
                ReturnError("缺少header:appId");
                return;
            }
            string time = request.Headers["time"].ToString();
            if (time.IsNullOrEmpty())
            {
                ReturnError("缺少header:time");
                return;
            }
            if (time.ToDateTime() < DateTime.Now.AddMinutes(-5) || time.ToDateTime() > DateTime.Now.AddMinutes(5))
            {
                ReturnError("time過期");
                return;
            }

            string guid = request.Headers["guid"].ToString();
            if (guid.IsNullOrEmpty())
            {
                ReturnError("缺少header:guid");
                return;
            }

            string guidKey = $"ApiGuid_{guid}";
            if (cache.GetString(guidKey).IsNullOrEmpty())
                cache.SetString(guidKey, "1", new DistributedCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
                });
            else
            {
                ReturnError("禁止重複呼叫!");
                return;
            }

            request.EnableBuffering();
            string body = await request.Body.ReadToStringAsync();

            string sign = request.Headers["sign"].ToString();
            if (sign.IsNullOrEmpty())
            {
                ReturnError("缺少header:sign");
                return;
            }

            string appSecret = await appSecretBus.GetAppSecretAsync(appId);
            if (appSecret.IsNullOrEmpty())
            {
                ReturnError("header:appId無效");
                return;
            }

            string newSign = HttpHelper.BuildApiSign(appId, appSecret, guid, time.ToDateTime(), body);
            if (sign != newSign)
            {
                string log =
                    $@"sign簽名錯誤!
                    headers:{request.Headers.ToJson()}
                    body:{body}
                    正確sign:{newSign}
                    ";
                logger.LogWarning(log);
                ReturnError("header:sign簽名錯誤");
                return;
            }

            void ReturnError(string msg)
            {
                filterContext.Result = Error(msg);
            }
        }
    }
}
namespace Core.Api
{
    /// <summary>
    /// 忽略介面簽名校驗
    /// </summary>
    public class IgnoreSignAttribute : BaseActionFilterAsync
    {

    }
}

相關文章