使用期限授权

parent cadad92f
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Performance.DtoModels;
using Performance.Infrastructure;
using System;
using System.IO;
using System.Threading.Tasks;
namespace Performance.Api
{
/// <summary>
/// 过期限制
/// </summary>
public class ExpirationLimitMiddleware
{
private readonly RequestDelegate _next;
public ExpirationLimitMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Path.StartsWithSegments("/api/function/limit"))
{
var response = new ApiResponse<LimitInformation>(ResponseType.OK, FunctionLimit.Limit);
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonHelper.Serialize(response));
return;
}
else if (FunctionLimit.Limit.ExpirationTime > DateTime.Now)
{
await _next.Invoke(context);
return;
}
else
{
var response = new ApiResponse(ResponseType.Expiration, $"{FunctionLimit.Limit.Remark},请联系易策商务!");
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonHelper.Serialize(response));
}
}
}
}
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using XC.RSAUtil;
namespace Performance.Api
{
public class LimitInformation
{
public DateTime ExpirationTime { get; set; }
public string Remark { get; internal set; }
}
public class FunctionLimit
{
public static LimitInformation Limit { get; } = new LimitInformation();
public static void Init()
{
var filePath = Path.Combine(Environment.CurrentDirectory, "secret.key");
if (!File.Exists(filePath))
{
Limit.ExpirationTime = DateTime.MinValue;
Limit.Remark = "授权文件无效;功能受限!";
return;
}
string content = ReadLimitContent(filePath);
if (string.IsNullOrEmpty(content))
{
Limit.ExpirationTime = DateTime.MinValue;
Limit.Remark = "授权文件发生错误;功能受限!";
return;
}
var timestamp = ConvertToExpiration(content);
if (timestamp == 0)
{
Limit.ExpirationTime = DateTime.MinValue;
Limit.Remark = "授权文件无法解析;功能受限!";
return;
}
Limit.ExpirationTime = (new DateTime(1970, 1, 1, 8, 0, 0, DateTimeKind.Unspecified)).AddSeconds(timestamp);
Limit.Remark = Limit.ExpirationTime > DateTime.Now ? "已授权开放使用!" : "授权过期,功能受限!";
}
private static long ConvertToExpiration(string content)
{
long result = 0;
try
{
var bigDataRsa = new RsaPkcs8Util(Encoding.UTF8, "", privateKey, 2048);
var timestamp = bigDataRsa.DecryptBigData(content, RSAEncryptionPadding.Pkcs1);
long.TryParse(timestamp, out result);
return result;
}
catch (Exception) { }
return result;
}
private static string ReadLimitContent(string filePath)
{
var content = "";
try
{
using (FileStream stream = new FileStream(filePath, FileMode.Open))
using (StreamReader reader = new StreamReader(stream))
{
content = reader.ReadToEnd();
}
}
catch (Exception) { }
return content;
}
private static string privateKey = @"-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC/XTloNsKshhr/
GC34GSQqKxiojkSWBZ+Xe3SxryqrYjx8yyjdrTgBq8lXOO9xtu+jr3XcFwHhFsq5
iK8qwRZQhinASjOFroeszrn0dbuLMT3ad+pCfdkXKcOwmCifHWLqODn0JXmPnTx5
8F1JD954J1Es8ugyJ6S77T0iPezmHvPgxV0Cn4E7Lg2114LwBgy1Kgb5S/b3pz5P
MQKECPRqK69SRIzUU7Nvw1LrqjK9OF5ZWYdGBlCBpRvbd0RIrgJ3NzAUCrE5t3Y+
KI3UM02FhoGzWM0j8oC/P6GGkNL8bY5JMR2TGWfUiB1UUjT+Y2hCCl0tfZUBWPDu
NVeqB9dxAgMBAAECggEAGOU56LLnFKbFsFYm9NXgfJPqu1L23UWSA5UOE2ekd3Nq
RxnvERfN53m/0dcYX4TbHEJhZOahWfUrHoQHtdo02vj5SYjdtxCDmhmy23jNk0gu
sdNT6J6StY67ZKgG8NxT2ADEmVyeue5MxdhdannkCWGkD+LyDkRWDBTLFT9VKIK4
dV22NdL7uvIYH+dP8fUYm6sM65+fAcPwj5bVPhCI90TjJo93e2/aBtzaMjdrRcfY
r8AaRMuY8m/QDvVhIaurki1JxG+Qwz4gT5eWhI8qUwGsx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isYqI5ElgWfl3t0sa8qq2I8fMso3a04AavJVzjvcbbvo6913BcB4RbKuYivKsEW
//UIYpwEozha6HrM659HW7izE92nfqQn3ZFynDsJgonx1i6jg59CV5j508efBdSQ/e
//eCdRLPLoMieku+09Ij3s5h7z4MVdAp+BOy4NtdeC8AYMtSoG+Uv296c+TzEChAj0
//aiuvUkSM1FOzb8NS66oyvTheWVmHRgZQgaUb23dESK4CdzcwFAqxObd2PiiN1DNN
//hYaBs1jNI/KAvz+hhpDS/G2OSTEdkxln1IgdVFI0/mNoQgpdLX2VAVjw7jVXqgfX
//cQIDAQAB
//-----END PUBLIC KEY-----";
}
}
using Microsoft.AspNetCore.Builder;
namespace Performance.Api
{
public static class RequestCultureMiddlewareExtensions
{
/// <summary>
/// 过期限制
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IApplicationBuilder UseExpirationLimit(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ExpirationLimitMiddleware>();
}
}
}
...@@ -24,6 +24,16 @@ ...@@ -24,6 +24,16 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Content Include="secret.key">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="XC.RSAUtil" Version="1.3.6" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.DtoModels\Performance.DtoModels.csproj" /> <ProjectReference Include="..\Performance.DtoModels\Performance.DtoModels.csproj" />
<ProjectReference Include="..\Performance.Services\Performance.Services.csproj" /> <ProjectReference Include="..\Performance.Services\Performance.Services.csproj" />
</ItemGroup> </ItemGroup>
......
...@@ -11,6 +11,7 @@ public class Program ...@@ -11,6 +11,7 @@ public class Program
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
FunctionLimit.Init();
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try try
{ {
......
...@@ -5,12 +5,14 @@ ...@@ -5,12 +5,14 @@
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Performance.Api.Configurations; using Performance.Api.Configurations;
using Performance.DtoModels;
using Performance.Infrastructure; using Performance.Infrastructure;
using Performance.Services; using Performance.Services;
using System.Globalization; using System.Globalization;
...@@ -112,6 +114,9 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) ...@@ -112,6 +114,9 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ {
app.UseStatusCodePagesWithReExecute("/error/{0}"); app.UseStatusCodePagesWithReExecute("/error/{0}");
} }
app.UseExpirationLimit();
app.UseRouting(); app.UseRouting();
app.UseAuthentication(); app.UseAuthentication();
...@@ -145,4 +150,5 @@ private void JsonOptions(MvcNewtonsoftJsonOptions json) ...@@ -145,4 +150,5 @@ private void JsonOptions(MvcNewtonsoftJsonOptions json)
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
} }
} }
} }
kR33WgheMa9iB6StfedFJcNte/VPFijyiMqP1eInuxqwaszl84XN0gaNPZAQjf9+NABj4cctSIKfolpUvEk8cGRRy349ud/cPA4mbY/yHQjBKjYczn2McgB8L+nl7t2SjBNUSSWovAsqYataxy0XXmiLSIi8ehTqwp6qWYHEmw/jnveeS5k381gZSZIiL7oqgkF1pOCYsGB72DreN2uT+Efy1wLz0lW4hIKmIoMK/ROVHYZLTcvpc1qNQODCdp0gqtYGcHUlv9uEcxcQMRrIwc4Mvppt/WNW6Dbg5RaXXDYhow4fLHRUabOK45qhYXhEDbR3oFAEXmodydQs+CaA9w==
\ No newline at end of file
...@@ -2026,6 +2026,18 @@ ...@@ -2026,6 +2026,18 @@
<param name="query"></param> <param name="query"></param>
<returns></returns> <returns></returns>
</member> </member>
<member name="T:Performance.Api.ExpirationLimitMiddleware">
<summary>
过期限制
</summary>
</member>
<member name="M:Performance.Api.RequestCultureMiddlewareExtensions.UseExpirationLimit(Microsoft.AspNetCore.Builder.IApplicationBuilder)">
<summary>
过期限制
</summary>
<param name="builder"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.ClaimService.GetUserId"> <member name="M:Performance.Api.ClaimService.GetUserId">
<summary> <summary>
获取当前请求登录ID 获取当前请求登录ID
......
...@@ -15,5 +15,6 @@ public enum ResponseType ...@@ -15,5 +15,6 @@ public enum ResponseType
Disable = 7, Disable = 7,
TooManyRequests = 8, TooManyRequests = 8,
Warning = 9, Warning = 9,
Expiration = 99,
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment