From 50843d43ff114cf6aa46f97b31afbdd8cf032424 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AD=99=E8=AF=9A?= Date: Sat, 10 Jan 2026 10:06:39 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BC=98=E5=8C=96=E9=A2=84=E7=AE=97?= =?UTF-8?q?=E6=8E=A7=E5=88=B6=E5=99=A8=E6=8E=92=E5=BA=8F=E9=80=BB=E8=BE=91?= =?UTF-8?q?=EF=BC=8C=E4=BF=AE=E5=A4=8D=E9=99=A4=E9=9B=B6=E9=94=99=E8=AF=AF?= =?UTF-8?q?=EF=BC=9B=E5=A2=9E=E5=BC=BA=E7=A8=8B=E5=BA=8F=E5=90=AF=E5=8A=A8?= =?UTF-8?q?=E6=97=B6=E7=9A=84JWT=E8=AE=A4=E8=AF=81=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- WebApi/Controllers/BudgetController.cs | 2 +- WebApi/Program.cs | 27 ++++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/WebApi/Controllers/BudgetController.cs b/WebApi/Controllers/BudgetController.cs index 80ee5d4..b81507c 100644 --- a/WebApi/Controllers/BudgetController.cs +++ b/WebApi/Controllers/BudgetController.cs @@ -19,7 +19,7 @@ public class BudgetController( .OrderBy(b => b.IsStopped) .OrderBy(b => b.Category) .ThenBy(b => b.Type) - .ThenByDescending(b => b.Current / b.Limit) + .ThenByDescending(b => b.Limit > 0 ? b.Current / b.Limit : 0) .ThenBy(b => b.Name) .ToList() .Ok(); diff --git a/WebApi/Program.cs b/WebApi/Program.cs index 17f336d..e3a874f 100644 --- a/WebApi/Program.cs +++ b/WebApi/Program.cs @@ -1,6 +1,7 @@ -using System.Text.Json.Serialization; using FreeSql; using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.IdentityModel.Tokens; using Scalar.AspNetCore; using Serilog; @@ -21,7 +22,14 @@ builder.Host.UseSerilog((context, loggerConfig) => }); // Add services to the container. -builder.Services.AddControllers(); +builder.Services.AddControllers(options => +{ + var policy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme) + .RequireAuthenticatedUser() + .Build(); + + options.Filters.Add(new AuthorizeFilter(policy)); +}); builder.Services.AddOpenApi(); builder.Services.AddHttpClient(); @@ -65,6 +73,21 @@ builder.Services.AddAuthentication(options => IssuerSigningKey = new SymmetricSecurityKey(key), ClockSkew = TimeSpan.Zero }; + options.Events = new JwtBearerEvents + { + OnChallenge = async context => + { + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + context.Response.ContentType = "application/json"; + await context.Response.WriteAsJsonAsync(BaseResponse.Fail("未登录")); + }, + OnForbidden = async context => + { + context.Response.StatusCode = StatusCodes.Status403Forbidden; + context.Response.ContentType = "application/json"; + await context.Response.WriteAsJsonAsync(BaseResponse.Fail("权限不足")); + } + }; }); builder.Services.AddAuthorization();