forked from xiongyuxing/tiku-backend.net
feat: harden SaaS authentication and authorization
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
@@ -8,7 +9,6 @@ using Microsoft.IdentityModel.Tokens;
|
||||
using Scalar.AspNetCore;
|
||||
using Serilog;
|
||||
using Serilog.Events;
|
||||
using System.Text;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.RateLimiting;
|
||||
using Tiku.Api.Logging;
|
||||
@@ -17,11 +17,13 @@ using Tiku.Api.OpenApi;
|
||||
using Tiku.Api.Options;
|
||||
using Tiku.Api.Security;
|
||||
using Tiku.Application;
|
||||
using Tiku.Application.Auth;
|
||||
using Tiku.Application.Security;
|
||||
using Tiku.Application.Tenancy;
|
||||
using Tiku.Infrastructure;
|
||||
using Tiku.Infrastructure.Commerce;
|
||||
using Tiku.Infrastructure.Persistence;
|
||||
using Tiku.Infrastructure.Security;
|
||||
using Tiku.Infrastructure.Storage;
|
||||
|
||||
Log.Logger = new LoggerConfiguration()
|
||||
@@ -116,11 +118,18 @@ try
|
||||
var rateLimitOptions = builder.Configuration
|
||||
.GetSection(ApiRateLimitOptions.SectionName)
|
||||
.Get<ApiRateLimitOptions>() ?? new ApiRateLimitOptions();
|
||||
if (rateLimitOptions.Enabled)
|
||||
builder.Services.AddOptions<AuthRateLimitOptions>()
|
||||
.Bind(builder.Configuration.GetSection(AuthRateLimitOptions.SectionName))
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
var authRateLimitOptions = builder.Configuration
|
||||
.GetSection(AuthRateLimitOptions.SectionName)
|
||||
.Get<AuthRateLimitOptions>() ?? new AuthRateLimitOptions();
|
||||
builder.Services.AddRateLimiter(options =>
|
||||
{
|
||||
builder.Services.AddRateLimiter(options =>
|
||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||
if (rateLimitOptions.Enabled)
|
||||
{
|
||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
|
||||
{
|
||||
var partitionKey =
|
||||
@@ -139,33 +148,113 @@ try
|
||||
Window = TimeSpan.FromSeconds(rateLimitOptions.WindowSeconds)
|
||||
});
|
||||
});
|
||||
options.OnRejected = async (context, cancellationToken) =>
|
||||
}
|
||||
|
||||
options.AddPolicy(
|
||||
AuthRateLimitPolicies.Password,
|
||||
httpContext => RateLimitPartition.GetFixedWindowLimiter(
|
||||
AuthRateLimitPartitionKey.Resolve(httpContext, AuthRateLimitPolicies.Password),
|
||||
_ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
AutoReplenishment = true,
|
||||
PermitLimit = authRateLimitOptions.PasswordPermitLimit,
|
||||
QueueLimit = 0,
|
||||
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
|
||||
Window = TimeSpan.FromSeconds(authRateLimitOptions.PasswordWindowSeconds)
|
||||
}));
|
||||
options.AddPolicy(
|
||||
AuthRateLimitPolicies.Sms,
|
||||
httpContext => RateLimitPartition.GetFixedWindowLimiter(
|
||||
AuthRateLimitPartitionKey.Resolve(httpContext, AuthRateLimitPolicies.Sms),
|
||||
_ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
AutoReplenishment = true,
|
||||
PermitLimit = authRateLimitOptions.SmsPermitLimit,
|
||||
QueueLimit = 0,
|
||||
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
|
||||
Window = TimeSpan.FromSeconds(authRateLimitOptions.SmsWindowSeconds)
|
||||
}));
|
||||
options.AddPolicy(
|
||||
AuthRateLimitPolicies.Mfa,
|
||||
httpContext => RateLimitPartition.GetFixedWindowLimiter(
|
||||
AuthRateLimitPartitionKey.Resolve(httpContext, AuthRateLimitPolicies.Mfa),
|
||||
_ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
AutoReplenishment = true,
|
||||
PermitLimit = authRateLimitOptions.MfaPermitLimit,
|
||||
QueueLimit = 0,
|
||||
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
|
||||
Window = TimeSpan.FromSeconds(authRateLimitOptions.MfaWindowSeconds)
|
||||
}));
|
||||
options.OnRejected = async (context, cancellationToken) =>
|
||||
{
|
||||
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
|
||||
{
|
||||
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
|
||||
{
|
||||
context.HttpContext.Response.Headers.RetryAfter = ((int)retryAfter.TotalSeconds).ToString();
|
||||
}
|
||||
context.HttpContext.Response.Headers.RetryAfter = ((int)retryAfter.TotalSeconds).ToString();
|
||||
}
|
||||
|
||||
var problem = new ProblemDetails
|
||||
{
|
||||
Title = "Too many requests.",
|
||||
Status = StatusCodes.Status429TooManyRequests,
|
||||
Instance = context.HttpContext.Request.Path
|
||||
};
|
||||
problem.Extensions["code"] = "rate_limited";
|
||||
problem.Extensions["traceId"] = context.HttpContext.TraceIdentifier;
|
||||
|
||||
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
||||
await context.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken);
|
||||
var problem = new ProblemDetails
|
||||
{
|
||||
Title = "Too many requests.",
|
||||
Status = StatusCodes.Status429TooManyRequests,
|
||||
Instance = context.HttpContext.Request.Path
|
||||
};
|
||||
});
|
||||
}
|
||||
problem.Extensions["code"] = "rate_limited";
|
||||
problem.Extensions["traceId"] = context.HttpContext.TraceIdentifier;
|
||||
|
||||
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
||||
await context.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken);
|
||||
};
|
||||
});
|
||||
|
||||
var connectionString = OptionsValidation.ResolveDatabaseConnectionString(
|
||||
builder.Configuration,
|
||||
builder.Environment.IsDevelopment());
|
||||
|
||||
builder.Services.AddInfrastructure(connectionString);
|
||||
|
||||
var requireProtectedDataProtectionKeys = !builder.Environment.IsDevelopment();
|
||||
builder.Services.AddOptions<DataProtectionKeyRingOptions>()
|
||||
.Bind(builder.Configuration.GetSection(DataProtectionKeyRingOptions.SectionName))
|
||||
.PostConfigure(options =>
|
||||
{
|
||||
options.ApplicationName =
|
||||
builder.Configuration["TIKU_DATA_PROTECTION_APPLICATION_NAME"] ?? options.ApplicationName;
|
||||
options.CertificatePath =
|
||||
builder.Configuration["TIKU_DATA_PROTECTION_CERTIFICATE_PATH"] ?? options.CertificatePath;
|
||||
options.CertificatePassword =
|
||||
builder.Configuration["TIKU_DATA_PROTECTION_CERTIFICATE_PASSWORD"] ?? options.CertificatePassword;
|
||||
})
|
||||
.Validate(
|
||||
options => DataProtectionKeyRingOptions.BeValid(options, requireProtectedDataProtectionKeys),
|
||||
"Data Protection requires an application name and, outside Development, an X509 certificate path.")
|
||||
.ValidateOnStart();
|
||||
|
||||
var dataProtectionOptions = builder.Configuration
|
||||
.GetSection(DataProtectionKeyRingOptions.SectionName)
|
||||
.Get<DataProtectionKeyRingOptions>() ?? new DataProtectionKeyRingOptions();
|
||||
dataProtectionOptions.ApplicationName =
|
||||
builder.Configuration["TIKU_DATA_PROTECTION_APPLICATION_NAME"] ?? dataProtectionOptions.ApplicationName;
|
||||
dataProtectionOptions.CertificatePath =
|
||||
builder.Configuration["TIKU_DATA_PROTECTION_CERTIFICATE_PATH"] ?? dataProtectionOptions.CertificatePath;
|
||||
dataProtectionOptions.CertificatePassword =
|
||||
builder.Configuration["TIKU_DATA_PROTECTION_CERTIFICATE_PASSWORD"] ?? dataProtectionOptions.CertificatePassword;
|
||||
if (!DataProtectionKeyRingOptions.BeValid(dataProtectionOptions, requireProtectedDataProtectionKeys))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Data Protection requires an application name and, outside Development, an X509 certificate path.");
|
||||
}
|
||||
|
||||
var dataProtection = builder.Services
|
||||
.AddDataProtection()
|
||||
.SetApplicationName(dataProtectionOptions.ApplicationName.Trim())
|
||||
.PersistKeysToDbContext<TikuDbContext>();
|
||||
var dataProtectionCertificate = dataProtectionOptions.LoadCertificate(requireProtectedDataProtectionKeys);
|
||||
if (dataProtectionCertificate is not null)
|
||||
{
|
||||
dataProtection.ProtectKeysWithCertificate(dataProtectionCertificate);
|
||||
}
|
||||
|
||||
builder.Services.Configure<ObjectStorageOptions>(
|
||||
builder.Configuration.GetSection(ObjectStorageOptions.SectionName));
|
||||
builder.Services.Configure<AliyunOssOptions>(
|
||||
@@ -215,6 +304,18 @@ try
|
||||
"Production tenant secret encryption cannot use the development master key.")
|
||||
.ValidateOnStart();
|
||||
|
||||
builder.Services.AddOptions<SmsSecurityOptions>()
|
||||
.Bind(builder.Configuration.GetSection(SmsSecurityOptions.SectionName))
|
||||
.PostConfigure(options =>
|
||||
{
|
||||
options.CodePepper = builder.Configuration["TIKU_SMS_CODE_PEPPER"] ?? options.CodePepper;
|
||||
})
|
||||
.Validate(
|
||||
SmsSecurityOptions.BeValid,
|
||||
"SMS security requires a pepper of at least 32 characters, exactly five verification attempts, " +
|
||||
"and positive tenant, phone, IP, and device rate limits.")
|
||||
.ValidateOnStart();
|
||||
|
||||
builder.Services.AddOptions<JwtOptions>()
|
||||
.Bind(builder.Configuration.GetSection("Security:Jwt"))
|
||||
.ValidateDataAnnotations()
|
||||
@@ -230,6 +331,7 @@ try
|
||||
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.MapInboundClaims = false;
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
@@ -237,57 +339,93 @@ try
|
||||
ValidateAudience = true,
|
||||
ValidAudience = jwtOptions.Audience,
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SigningKey)),
|
||||
RequireSignedTokens = true,
|
||||
ValidAlgorithms = [SecurityAlgorithms.RsaSha256],
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromMinutes(1)
|
||||
RequireExpirationTime = true,
|
||||
ClockSkew = TimeSpan.FromMinutes(1),
|
||||
NameClaimType = TikuClaimTypes.UserId
|
||||
};
|
||||
options.Events = new JwtBearerEvents
|
||||
{
|
||||
OnTokenValidated = async context =>
|
||||
{
|
||||
var tenantIdValue = context.Principal?.FindFirst(TikuClaimTypes.TenantId)?.Value;
|
||||
if (!Guid.TryParse(tenantIdValue, out var tenantId))
|
||||
var principal = context.Principal;
|
||||
if (!Guid.TryParse(principal?.FindFirst(TikuClaimTypes.UserId)?.Value, out var userId) ||
|
||||
!Guid.TryParse(principal?.FindFirst(TikuClaimTypes.SessionId)?.Value, out var sessionId) ||
|
||||
string.IsNullOrWhiteSpace(principal?.FindFirst(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti)?.Value) ||
|
||||
!long.TryParse(
|
||||
principal?.FindFirst(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Iat)?.Value,
|
||||
System.Globalization.NumberStyles.None,
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
out _))
|
||||
{
|
||||
context.Fail("Missing tenant claim.");
|
||||
context.Fail("Missing or invalid subject/session/jti/iat claim.");
|
||||
return;
|
||||
}
|
||||
|
||||
var realmValue = principal.FindFirst(TikuClaimTypes.Realm)?.Value;
|
||||
var realm = string.Equals(realmValue, "tenant", StringComparison.Ordinal)
|
||||
? Tiku.Domain.Tenancy.AuthRealm.Tenant
|
||||
: string.Equals(realmValue, "platform", StringComparison.Ordinal)
|
||||
? Tiku.Domain.Tenancy.AuthRealm.Platform
|
||||
: (Tiku.Domain.Tenancy.AuthRealm?)null;
|
||||
var tenantIdValue = principal.FindFirst(TikuClaimTypes.TenantId)?.Value;
|
||||
var tenantId = Guid.TryParse(tenantIdValue, out var parsedTenantId)
|
||||
? parsedTenantId
|
||||
: (Guid?)null;
|
||||
if (realm is null || (realm == Tiku.Domain.Tenancy.AuthRealm.Tenant) != tenantId.HasValue)
|
||||
{
|
||||
context.Fail("Token scope and tenant claims are inconsistent.");
|
||||
return;
|
||||
}
|
||||
|
||||
var resolutionOptions = context.HttpContext.RequestServices
|
||||
.GetRequiredService<Microsoft.Extensions.Options.IOptions<TenantResolutionOptions>>().Value;
|
||||
var requestHost = context.HttpContext.Request.Host.Host.Trim().TrimEnd('.');
|
||||
var isPlatformHost = resolutionOptions.PlatformHosts.Any(host =>
|
||||
string.Equals(host.Trim().TrimEnd('.'), requestHost, StringComparison.OrdinalIgnoreCase));
|
||||
var resolvedTenantContext = context.HttpContext.RequestServices.GetRequiredService<ITenantContext>();
|
||||
var tenantInitializer = context.HttpContext.RequestServices
|
||||
.GetRequiredService<ITenantContextInitializer>();
|
||||
try
|
||||
if (realm == Tiku.Domain.Tenancy.AuthRealm.Platform)
|
||||
{
|
||||
tenantInitializer.Initialize(tenantId, null, TenantResolutionSource.Jwt);
|
||||
if (!isPlatformHost || resolvedTenantContext.IsResolved)
|
||||
{
|
||||
context.HttpContext.Items["tenant_context_conflict"] = true;
|
||||
context.Fail("Platform tokens are only valid on a platform host.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (TenantContextConflictException)
|
||||
else
|
||||
{
|
||||
context.HttpContext.Items["tenant_context_conflict"] = true;
|
||||
context.Fail("Authenticated tenant does not match the request host.");
|
||||
return;
|
||||
if (isPlatformHost && !resolvedTenantContext.IsResolved)
|
||||
{
|
||||
context.HttpContext.Items["tenant_context_conflict"] = true;
|
||||
context.Fail("Tenant tokens on a platform host require a matching tenant code.");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
tenantInitializer.Initialize(tenantId!.Value, null, TenantResolutionSource.Jwt);
|
||||
}
|
||||
catch (TenantContextConflictException)
|
||||
{
|
||||
context.HttpContext.Items["tenant_context_conflict"] = true;
|
||||
context.Fail("Authenticated tenant does not match the request host.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!jwtOptions.ValidateSessions)
|
||||
var sessionStore = context.HttpContext.RequestServices.GetRequiredService<IAuthSessionStore>();
|
||||
var session = await sessionStore.ValidateAccessSessionAsync(
|
||||
sessionId, userId, realm.Value, tenantId, context.HttpContext.RequestAborted);
|
||||
var tokenMfaSatisfied = principal.FindAll(TikuClaimTypes.Mfa)
|
||||
.Any(claim => string.Equals(claim.Value, "mfa", StringComparison.Ordinal));
|
||||
if (session is null || session.MfaSatisfied != tokenMfaSatisfied)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var sessionIdValue = context.Principal?.FindFirst(TikuClaimTypes.SessionId)?.Value;
|
||||
if (!Guid.TryParse(sessionIdValue, out var sessionId))
|
||||
{
|
||||
context.Fail("Missing session claim.");
|
||||
return;
|
||||
}
|
||||
|
||||
var dbContext = context.HttpContext.RequestServices.GetRequiredService<TikuDbContext>();
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var isSessionActive = await dbContext.AuthSessions.AnyAsync(
|
||||
session =>
|
||||
session.Id == sessionId &&
|
||||
session.RevokedAt == null &&
|
||||
session.ExpiresAt > now);
|
||||
|
||||
if (!isSessionActive)
|
||||
{
|
||||
context.Fail("Session has been revoked or expired.");
|
||||
context.Fail("Session, identity, membership, tenant, role or MFA state is no longer valid.");
|
||||
}
|
||||
},
|
||||
OnChallenge = async context =>
|
||||
@@ -307,32 +445,44 @@ try
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
|
||||
.Configure<IJwtKeyRing>((options, keyRing) =>
|
||||
{
|
||||
options.TokenValidationParameters.IssuerSigningKeys = keyRing.ValidationKeys;
|
||||
options.TokenValidationParameters.TryAllIssuerSigningKeys = false;
|
||||
options.TokenValidationParameters.IssuerSigningKeyResolver = (_, _, kid, _) =>
|
||||
string.IsNullOrWhiteSpace(kid)
|
||||
? []
|
||||
: keyRing.ValidationKeys.Where(key =>
|
||||
string.Equals(key.KeyId, kid, StringComparison.Ordinal));
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization(options =>
|
||||
{
|
||||
options.FallbackPolicy = new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder()
|
||||
.RequireAuthenticatedUser()
|
||||
.Build();
|
||||
options.AddPolicy(
|
||||
TikuPolicies.AuthenticatedUser,
|
||||
policy => policy.RequireAuthenticatedUser());
|
||||
options.AddPolicy(
|
||||
TikuPolicies.CurrentTenantMember,
|
||||
policy => policy
|
||||
.RequireAuthenticatedUser()
|
||||
.RequireAssertion(context => TenantRoleAuthorization.IsTenantMember(context.User)));
|
||||
options.AddPolicy(
|
||||
TikuPolicies.TenantAdmin,
|
||||
policy => policy
|
||||
.RequireAuthenticatedUser()
|
||||
.RequireAssertion(context => TenantRoleAuthorization.IsTenantAdmin(context.User)));
|
||||
policy => policy.RequireAuthenticatedUser());
|
||||
});
|
||||
builder.Services.AddTikuRbacAuthorization();
|
||||
builder.Services.AddSingleton<Microsoft.AspNetCore.Authorization.IAuthorizationMiddlewareResultHandler,
|
||||
AuditingAuthorizationMiddlewareResultHandler>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
app.MapOpenApi().AllowAnonymous();
|
||||
app.MapScalarApiReference(options => options
|
||||
.WithTitle("TIKU Backend API")
|
||||
.AddPreferredSecuritySchemes("BearerAuth")
|
||||
.EnablePersistentAuthentication());
|
||||
.EnablePersistentAuthentication())
|
||||
.AllowAnonymous();
|
||||
}
|
||||
|
||||
app.UseSerilogRequestLogging(SerilogRequestLogging.ConfigureRequestLogging);
|
||||
@@ -343,10 +493,8 @@ try
|
||||
app.UseCors(CorsOptions.PolicyName);
|
||||
app.UseMiddleware<TenantResolutionMiddleware>();
|
||||
app.UseAuthentication();
|
||||
if (rateLimitOptions.Enabled)
|
||||
{
|
||||
app.UseRateLimiter();
|
||||
}
|
||||
app.UseMiddleware<AuthRateLimitPartitionMiddleware>();
|
||||
app.UseRateLimiter();
|
||||
|
||||
app.UseMiddleware<CurrentPrincipalMiddleware>();
|
||||
app.UseAuthorization();
|
||||
|
||||
Reference in New Issue
Block a user