using Kean.Application.Command.Interfaces; using Kean.Infrastructure.Soap; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.SignalR; using System.Threading.Tasks; namespace Kean.Presentation.Rest { /// /// 身份验证中间件 /// public class AuthenticationMiddleware { private readonly RequestDelegate _next; // 管道 /// /// 初始化 Kean.Presentation.Rest.AuthenticationMiddleware 类的新实例 /// public AuthenticationMiddleware(RequestDelegate next) { _next = next; } /// /// 执行方法 /// public async Task InvokeAsync(HttpContext context, IIdentityService service) { // 令牌 var token = context.Request.Headers["Token"]; if (token.Count > 0) { context.Items["token"] = token.ToString(); } var endpoint = context.Features.Get()?.Endpoint; if (endpoint == null) { context.Response.StatusCode = 404; } else { // 对未标记 Anonymous 特性的 Action 以及非 SignalR 进行身份验证 if (endpoint.Metadata.GetMetadata() != null || endpoint.Metadata.GetMetadata() != null || endpoint.Metadata.GetMetadata() != null) { await _next(context); } else { if (token.Count == 0) { context.Response.StatusCode = 401; } else { var session = await service.Authenticate(token); if (session.HasValue) { context.Items["session"] = session.Value; await _next(context); } else { context.Response.StatusCode = 401; } } } } } } }