添加了自定义 Token 的验证

This commit is contained in:
milimoe 2024-12-29 22:11:30 +08:00
parent 03a56e7b57
commit 146517ecf7
Signed by: milimoe
GPG Key ID: 05D280912DA6C69E
2 changed files with 51 additions and 2 deletions

View File

@ -0,0 +1,44 @@
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using Milimoe.FunGame.Core.Api.Utility;
namespace Milimoe.FunGame.WebAPI.Architecture
{
public class CustomBearerAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
// 检查是否有 Authorization Header
if (!Request.Headers.TryGetValue("Authorization", out Microsoft.Extensions.Primitives.StringValues value))
{
return AuthenticateResult.Fail("Authorization header is missing.");
}
string authorizationHeader = value.ToString();
if (!authorizationHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
return AuthenticateResult.Fail("Invalid Authorization header format.");
}
string token = authorizationHeader["Bearer ".Length..].Trim();
// 验证自定义 Token
string name = WebAPIAuthenticator.ValidateToken(token);
if (name == "")
{
await Task.Delay(1);
return AuthenticateResult.Fail("Invalid Token.");
}
// 如果验证通过,创建 ClaimsIdentity
Claim[] claims = [new Claim(ClaimTypes.Name, name)];
ClaimsIdentity identity = new(claims, Scheme.Name);
ClaimsPrincipal principal = new(identity);
AuthenticationTicket ticket = new(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
}
}

View File

@ -4,6 +4,7 @@ using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json.Serialization;
using System.Text.Unicode;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
@ -147,7 +148,11 @@ try
});
// Ìí¼Ó JWT ÈÏÖ¤
builder.Services.AddScoped<JWTService>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
@ -159,7 +164,7 @@ try
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"] ?? "undefined"))
};
});
}).AddScheme<AuthenticationSchemeOptions, CustomBearerAuthenticationHandler>("CustomBearer", options => { });
WebApplication app = builder.Build();