62 lines
2.4 KiB
C#
62 lines
2.4 KiB
C#
using FutureMailAPI.Services;
|
||
using FutureMailAPI.Models;
|
||
|
||
namespace FutureMailAPI.Middleware
|
||
{
|
||
public class OAuthAuthenticationMiddleware
|
||
{
|
||
private readonly RequestDelegate _next;
|
||
private readonly ILogger<OAuthAuthenticationMiddleware> _logger;
|
||
|
||
public OAuthAuthenticationMiddleware(RequestDelegate next, ILogger<OAuthAuthenticationMiddleware> logger)
|
||
{
|
||
_next = next;
|
||
_logger = logger;
|
||
}
|
||
|
||
public async Task InvokeAsync(HttpContext context, IOAuthService oauthService)
|
||
{
|
||
// 检查是否需要OAuth认证
|
||
var endpoint = context.GetEndpoint();
|
||
if (endpoint != null)
|
||
{
|
||
// 如果端点标记为AllowAnonymous,则跳过认证
|
||
var allowAnonymousAttribute = endpoint.Metadata.GetMetadata<Microsoft.AspNetCore.Authorization.AllowAnonymousAttribute>();
|
||
if (allowAnonymousAttribute != null)
|
||
{
|
||
await _next(context);
|
||
return;
|
||
}
|
||
}
|
||
|
||
// 检查Authorization头
|
||
var authHeader = context.Request.Headers.Authorization.FirstOrDefault();
|
||
if (authHeader != null && authHeader.StartsWith("Bearer "))
|
||
{
|
||
var token = authHeader.Substring("Bearer ".Length).Trim();
|
||
|
||
// 验证令牌
|
||
var validationResult = await oauthService.ValidateTokenAsync(token);
|
||
if (validationResult.Success)
|
||
{
|
||
// 获取访问令牌信息
|
||
var accessToken = await oauthService.GetAccessTokenAsync(token);
|
||
if (accessToken != null)
|
||
{
|
||
// 将用户信息添加到HttpContext
|
||
context.Items["UserId"] = accessToken.UserId;
|
||
context.Items["UserEmail"] = accessToken.User.Email;
|
||
context.Items["AccessToken"] = accessToken;
|
||
|
||
await _next(context);
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 如果没有有效的令牌,返回401未授权
|
||
context.Response.StatusCode = 401;
|
||
await context.Response.WriteAsync("未授权访问");
|
||
}
|
||
}
|
||
} |