forked from gongxuegit/tiku-backend.net
feat: add api security foundation
This commit is contained in:
46
Tiku.Api/Controllers/SecurityDiagnosticsController.cs
Normal file
46
Tiku.Api/Controllers/SecurityDiagnosticsController.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Tiku.Application.Security;
|
||||
|
||||
namespace Tiku.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[ApiExplorerSettings(IgnoreApi = true)]
|
||||
[Route("api/_security")]
|
||||
public sealed class SecurityDiagnosticsController(
|
||||
ICurrentUser currentUser,
|
||||
ICurrentTenant currentTenant) : ControllerBase
|
||||
{
|
||||
[Authorize(Policy = TikuPolicies.AuthenticatedUser)]
|
||||
[HttpGet("authenticated")]
|
||||
public ActionResult<object> Authenticated()
|
||||
{
|
||||
return Ok(new
|
||||
{
|
||||
currentUser.UserId,
|
||||
currentUser.IsAuthenticated
|
||||
});
|
||||
}
|
||||
|
||||
[Authorize(Policy = TikuPolicies.CurrentTenantMember)]
|
||||
[HttpGet("tenant-member")]
|
||||
public ActionResult<object> TenantMember()
|
||||
{
|
||||
return Ok(new
|
||||
{
|
||||
currentTenant.TenantId,
|
||||
currentTenant.Role
|
||||
});
|
||||
}
|
||||
|
||||
[Authorize(Policy = TikuPolicies.TenantAdmin)]
|
||||
[HttpGet("tenant-admin")]
|
||||
public ActionResult<object> TenantAdmin()
|
||||
{
|
||||
return Ok(new
|
||||
{
|
||||
currentTenant.TenantId,
|
||||
currentTenant.Role
|
||||
});
|
||||
}
|
||||
}
|
||||
16
Tiku.Api/Middleware/CurrentPrincipalMiddleware.cs
Normal file
16
Tiku.Api/Middleware/CurrentPrincipalMiddleware.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using Tiku.Application.Security;
|
||||
|
||||
namespace Tiku.Api.Middleware;
|
||||
|
||||
public sealed class CurrentPrincipalMiddleware(RequestDelegate next)
|
||||
{
|
||||
public async Task InvokeAsync(
|
||||
HttpContext context,
|
||||
ICurrentUser currentUser,
|
||||
ICurrentTenant currentTenant)
|
||||
{
|
||||
currentUser.Load(context.User);
|
||||
currentTenant.Load(context.User);
|
||||
await next(context);
|
||||
}
|
||||
}
|
||||
33
Tiku.Api/Middleware/ExceptionHandlingMiddleware.cs
Normal file
33
Tiku.Api/Middleware/ExceptionHandlingMiddleware.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Tiku.Api.Middleware;
|
||||
|
||||
public sealed class ExceptionHandlingMiddleware(
|
||||
RequestDelegate next,
|
||||
ILogger<ExceptionHandlingMiddleware> logger,
|
||||
IHostEnvironment environment)
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogError(exception, "Unhandled API exception");
|
||||
|
||||
var problem = new ProblemDetails
|
||||
{
|
||||
Title = "An unexpected error occurred.",
|
||||
Status = StatusCodes.Status500InternalServerError,
|
||||
Detail = environment.IsDevelopment() ? exception.Message : null,
|
||||
Instance = context.Request.Path
|
||||
};
|
||||
|
||||
problem.Extensions["traceId"] = context.TraceIdentifier;
|
||||
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
await context.Response.WriteAsJsonAsync(problem);
|
||||
}
|
||||
}
|
||||
}
|
||||
19
Tiku.Api/Options/JwtOptions.cs
Normal file
19
Tiku.Api/Options/JwtOptions.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
|
||||
namespace Tiku.Api.Options;
|
||||
|
||||
public sealed class JwtOptions
|
||||
{
|
||||
public string Issuer { get; set; } = "tiku-backend";
|
||||
public string Audience { get; set; } = "tiku-api";
|
||||
public string SigningKey { get; set; } = "development-only-tiku-signing-key-change-before-production";
|
||||
public int AccessTokenMinutes { get; set; } = 30;
|
||||
public int RefreshTokenDays { get; set; } = 30;
|
||||
|
||||
public SymmetricSecurityKey CreateSecurityKey()
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(SigningKey);
|
||||
return new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SigningKey));
|
||||
}
|
||||
}
|
||||
@@ -1,40 +1,86 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Scalar.AspNetCore;
|
||||
using Tiku.Api.Middleware;
|
||||
using Tiku.Api.Options;
|
||||
using Tiku.Api.Security;
|
||||
using Tiku.Application;
|
||||
using Tiku.Application.Security;
|
||||
using Tiku.Infrastructure;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddOpenApi();
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddApplication();
|
||||
|
||||
var connectionString =
|
||||
builder.Configuration.GetConnectionString("Database") ??
|
||||
builder.Configuration["DATABASE_URL"] ??
|
||||
"Host=localhost;Database=tiku;Username=postgres";
|
||||
|
||||
builder.Services.AddInfrastructure(connectionString);
|
||||
|
||||
builder.Services.Configure<JwtOptions>(builder.Configuration.GetSection("Security:Jwt"));
|
||||
var jwtOptions = builder.Configuration
|
||||
.GetSection("Security:Jwt")
|
||||
.Get<JwtOptions>() ?? new JwtOptions();
|
||||
|
||||
builder.Services
|
||||
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = jwtOptions.Issuer,
|
||||
ValidateAudience = true,
|
||||
ValidAudience = jwtOptions.Audience,
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = jwtOptions.CreateSecurityKey(),
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromMinutes(1)
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization(options =>
|
||||
{
|
||||
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)));
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
app.MapScalarApiReference();
|
||||
}
|
||||
|
||||
app.UseMiddleware<ExceptionHandlingMiddleware>();
|
||||
app.UseHttpsRedirection();
|
||||
app.UseAuthentication();
|
||||
app.UseMiddleware<CurrentPrincipalMiddleware>();
|
||||
app.UseAuthorization();
|
||||
|
||||
var summaries = new[]
|
||||
{
|
||||
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
||||
};
|
||||
|
||||
app.MapGet("/weatherforecast", () =>
|
||||
{
|
||||
var forecast = Enumerable.Range(1, 5).Select(index =>
|
||||
new WeatherForecast
|
||||
(
|
||||
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
|
||||
Random.Shared.Next(-20, 55),
|
||||
summaries[Random.Shared.Next(summaries.Length)]
|
||||
))
|
||||
.ToArray();
|
||||
return forecast;
|
||||
})
|
||||
.WithName("GetWeatherForecast");
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
|
||||
public partial class Program;
|
||||
|
||||
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
|
||||
{
|
||||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
||||
|
||||
30
Tiku.Api/Security/TenantRoleAuthorization.cs
Normal file
30
Tiku.Api/Security/TenantRoleAuthorization.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using System.Security.Claims;
|
||||
using Tiku.Application.Security;
|
||||
using Tiku.Domain.Tenancy;
|
||||
|
||||
namespace Tiku.Api.Security;
|
||||
|
||||
internal static class TenantRoleAuthorization
|
||||
{
|
||||
private static readonly HashSet<string> AdminRoles = new(StringComparer.Ordinal)
|
||||
{
|
||||
TenantRole.PlatformAdmin.ToString(),
|
||||
TenantRole.TenantOwner.ToString(),
|
||||
TenantRole.TenantAdmin.ToString()
|
||||
};
|
||||
|
||||
public static bool IsTenantMember(ClaimsPrincipal principal)
|
||||
{
|
||||
return principal.Identity?.IsAuthenticated == true &&
|
||||
principal.HasClaim(claim => claim.Type == TikuClaimTypes.TenantId);
|
||||
}
|
||||
|
||||
public static bool IsTenantAdmin(ClaimsPrincipal principal)
|
||||
{
|
||||
return IsTenantMember(principal) &&
|
||||
principal.Claims
|
||||
.Where(claim => claim.Type == TikuClaimTypes.TenantRole)
|
||||
.Select(claim => claim.Value)
|
||||
.Any(role => AdminRoles.Contains(role));
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,11 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" />
|
||||
<PackageReference Include="Microsoft.OpenApi" />
|
||||
<PackageReference Include="Scalar.AspNetCore" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -5,5 +5,14 @@
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Security": {
|
||||
"Jwt": {
|
||||
"Issuer": "tiku-backend",
|
||||
"Audience": "tiku-api",
|
||||
"SigningKey": "development-only-tiku-signing-key-change-before-production",
|
||||
"AccessTokenMinutes": 30,
|
||||
"RefreshTokenDays": 30
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user