新建standard类库项目,添加引用包

Microsoft.AspNetCore

 

1、扩展IApplicationBuilder

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Options;
using System;

namespace MiddleWareLib.Middlewares
{
    public static class PracticeAuthenticationExtensions
    {
        public static IApplicationBuilder UsePracticeAuthentication(this IApplicationBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            return builder.UseMiddleware<PracticeAuthenticationMiddleware>();
        }

        public static IApplicationBuilder UsePracticeAuthentication(this IApplicationBuilder builder, PracticeAuthenticationOptions options)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return builder.UseMiddleware<PracticeAuthenticationOptions>(Options.Create(options));
        }
    }
}

 

2、定义中间件

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace MiddleWareLib
{
    public class PracticeAuthenticationMiddleware
    {
        private readonly PracticeAuthenticationOptions _options;

        private readonly RequestDelegate _next;

        public PracticeAuthenticationMiddleware(RequestDelegate next, IOptions<PracticeAuthenticationOptions> options)
        {
            this._next = next;
            this._options = options.Value;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            await Check(context);
            await _next.Invoke(context);
        }



        #region MyRegion
        /// <summary>
        /// the main check method
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requestInfo"></param>
        /// <returns></returns>
        private async Task Check(HttpContext context)
        {
            string computeSinature =$"{context.Request.Query["appid"]}-{context.Request.Query["timestamp"]}";
            double tmpTimestamp;
            if (computeSinature.Equals(context.Request.Query["sign"]) &&
                double.TryParse(context.Request.Query["timestamp"], out tmpTimestamp))
            {
                if (CheckExpiredTime(tmpTimestamp, _options.ExpiredSecond))
                {
                    await ReturnResponse(context,408, "验证失败");
                }
                else
                {
                    await ReturnResponse(context, 200, "验证成功");
                }
            }
            else
            {
                await ReturnResponse(context);
            }
        }
        /// <summary>
        ///响应 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private async Task ReturnResponse(HttpContext context,int statu=200,string msg= "Time Out!")
        {
            context.Response.StatusCode = statu;
            await context.Response.WriteAsync(JsonConvert.SerializeObject(new{ Code = statu, Message =msg }));
        }
        /// <summary>
        /// 签名超时
        /// </summary>
        /// <param name="timestamp"></param>
        /// <param name="expiredSecond"></param>
        /// <returns></returns>
        private bool CheckExpiredTime(double timestamp, double expiredSecond)
        {
            double now_timestamp = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
            return (now_timestamp - timestamp) > expiredSecond;
        }
        #endregion
    }
}

 

3、自定义中间件配置

using System;
using System.Collections.Generic;
using System.Text;

namespace MiddleWareLib
{
    public class PracticeAuthenticationOptions
    {
        public string EncryptKey { get; set; }

        public int ExpiredSecond { get; set; }
    }
}

 

4、扩展IServiceCollection

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.DependencyInjection;

namespace MiddleWareLib
{
    public static class PracticeAuthenticationServicesExtensions
    {
        public static IServiceCollection AddPracticeAuthentication(this IServiceCollection services)
        {
            if (services==null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            return services;
        }
        public static IServiceCollection AddPracticeAuthentication(this IServiceCollection services,Action<PracticeAuthenticationOptions> PracticeAuthenticationOptions)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            if(PracticeAuthenticationOptions == null)
            {
                throw new ArgumentNullException(nameof(PracticeAuthenticationOptions));
            }
            services.Configure(PracticeAuthenticationOptions);
            return services;
        }
    }
}

 

相关文章: