WMSlite/WmsLite.Api/Infrastructure/AuthServiceCollectionExtensions.cs
zhougf fa1b286463 Add WmsLite monorepo with JWT auth, tenant context, and project READMEs.
Implement API security baseline (sys_user, JWT, audit fields, transactions,
unique constraints) and Web real login with 401 handling. Document setup
and development workflows in root, WmsLite.Api, and WmsLite.Web README files.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-24 14:17:47 +08:00

64 lines
2.6 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using WmsLite.Api.Common;
using WmsLite.Api.Infrastructure.Auth;
namespace WmsLite.Api.Infrastructure;
public static class AuthServiceCollectionExtensions
{
public static IServiceCollection AddWmsLiteAuth(this IServiceCollection services, IConfiguration configuration)
{
services.Configure<JwtOptions>(configuration.GetSection(JwtOptions.SectionName));
services.AddScoped<ICurrentUserContext, HttpCurrentUserContext>();
services.AddSingleton<IJwtTokenService, JwtTokenService>();
var jwt = configuration.GetSection(JwtOptions.SectionName).Get<JwtOptions>() ?? new JwtOptions();
if (string.IsNullOrWhiteSpace(jwt.Key))
{
throw new InvalidOperationException(
"Jwt:Key is not configured. Set Jwt:Key in user-secrets or environment variables.");
}
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// 保留 JWT 原始 claim 名(sub、tenant_id 等),避免映射后 ICurrentUserContext 读不到
options.MapInboundClaims = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwt.Issuer,
ValidAudience = jwt.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.Key)),
ClockSkew = TimeSpan.FromMinutes(1),
};
options.Events = new JwtBearerEvents
{
OnChallenge = async context =>
{
context.HandleResponse();
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.ContentType = "application/json; charset=utf-8";
await context.Response.WriteAsJsonAsync(
BusinessResult.Fail("Unauthorized.", "401"));
},
};
});
services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
return services;
}
}