Files
StoreWeb/StoreHub.Framework/Security/JwtBearerResponseHandler.cs
T
2026-08-14 18:00:58 +08:00

46 lines
1.4 KiB
C#
Raw 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 Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using StoreHub.Framework.Commons;
using System.Text;
using System.Text.Json;
namespace StoreHub.Framework.Security;
/// <summary>
/// JwtBearer 认证失败/授权失败时,统一返回 <see cref="ApiResult{T}"/> 格式的 JSON 响应。
/// </summary>
internal static class JwtBearerResponseHandler
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
/// <summary>
/// 未携带令牌或令牌无效(401)
/// </summary>
public static Task OnChallenge(JwtBearerChallengeContext context)
{
context.HandleResponse();
return WriteAsync(context.HttpContext, StatusCodes.Status401Unauthorized, "未授权:请先登录或携带有效的访问令牌");
}
/// <summary>
/// 已认证但无权限(403)
/// </summary>
public static Task OnForbidden(ForbiddenContext context)
{
return WriteAsync(context.HttpContext, StatusCodes.Status403Forbidden, "禁止访问:当前账号没有权限执行该操作");
}
private static async Task WriteAsync(HttpContext httpContext, int statusCode, string message)
{
httpContext.Response.StatusCode = statusCode;
httpContext.Response.ContentType = "application/json; charset=utf-8";
string body = JsonSerializer.Serialize(ApiResult.Error(message, statusCode), JsonOptions);
await httpContext.Response.WriteAsync(body, Encoding.UTF8);
}
}