2020-02-04 16:51:15 +08:00
|
|
|
using System.Text.Json;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
|
using Microsoft.Extensions.Caching.Distributed;
|
2020-08-05 15:29:56 +08:00
|
|
|
using SimApi.Communications;
|
2020-02-04 16:51:15 +08:00
|
|
|
|
2024-03-23 07:29:43 +08:00
|
|
|
namespace SimApi.Middlewares;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 认证信息获取中间件
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class SimApiAuthMiddleware(RequestDelegate next)
|
2020-02-04 16:51:15 +08:00
|
|
|
{
|
2024-03-23 07:29:43 +08:00
|
|
|
public Task Invoke(HttpContext httpContext, IDistributedCache cache)
|
2020-02-04 16:51:15 +08:00
|
|
|
{
|
2024-03-23 07:29:43 +08:00
|
|
|
string token = null;
|
|
|
|
|
if (httpContext.Request.Headers.TryGetValue("Token", out var header))
|
2020-02-04 16:51:15 +08:00
|
|
|
{
|
2024-03-23 07:29:43 +08:00
|
|
|
token = header;
|
2020-02-04 16:51:15 +08:00
|
|
|
}
|
|
|
|
|
|
2024-03-23 07:29:43 +08:00
|
|
|
if (!string.IsNullOrEmpty(token))
|
2020-02-04 16:51:15 +08:00
|
|
|
{
|
2024-03-23 07:29:43 +08:00
|
|
|
var login = cache.GetString(token);
|
|
|
|
|
if (login != null)
|
2020-02-04 16:51:15 +08:00
|
|
|
{
|
2024-03-23 07:29:43 +08:00
|
|
|
httpContext.Items.Add("LoginInfo", JsonSerializer.Deserialize<SimApiLoginItem>(login));
|
2020-02-04 16:51:15 +08:00
|
|
|
}
|
|
|
|
|
}
|
2024-03-23 07:29:43 +08:00
|
|
|
|
|
|
|
|
return next(httpContext);
|
2020-02-04 16:51:15 +08:00
|
|
|
}
|
2024-03-23 07:29:43 +08:00
|
|
|
}
|