Files
simapi-net/Middlewares/SimApiAuthMiddleware.cs
T

31 lines
845 B
C#
Raw Normal View History

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;
2024-03-24 17:31:22 +08:00
using SimApi.Helpers;
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-24 17:31:22 +08:00
public Task Invoke(HttpContext httpContext, IDistributedCache cache, SimApiAuth auth)
2020-02-04 16:51:15 +08:00
{
2024-07-26 08:11:21 +08:00
string? token = null;
2024-03-23 07:29:43 +08:00
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-07-26 08:11:21 +08:00
if (string.IsNullOrEmpty(token)) return next(httpContext);
var login = auth.GetLogin(token);
if (login != null)
2020-02-04 16:51:15 +08:00
{
2024-07-26 08:11:21 +08:00
httpContext.Items.Add("LoginInfo", 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
}