46 lines
1.4 KiB
C#
46 lines
1.4 KiB
C#
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);
|
||
}
|
||
}
|
||
|