Files
SocialPub/PrivaPub/Services/JwtEvents.cs
T

52 lines
1.8 KiB
C#
Raw Normal View History

2023-02-18 08:52:17 +01:00
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Localization;
2023-02-19 00:43:43 +01:00
using PrivaPub.ClientModels;
using PrivaPub.Resources;
2023-02-18 08:52:17 +01:00
using System.Text;
using System.Text.Json;
2023-02-19 00:43:43 +01:00
namespace PrivaPub.Services
2023-02-18 08:52:17 +01:00
{
public class JwtEvents : JwtBearerEvents
{
ILogger<JwtEvents> _logger { get; set; }
const string contentType = "application/json";
2026-10-03 10:46:20 +02:00
public override async Task Challenge(JwtBearerChallengeContext context)
2023-02-18 08:52:17 +01:00
{
2026-10-03 10:46:20 +02:00
context.HandleResponse();
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.Headers.WWWAuthenticate = context.AuthenticateFailure == default ? "Bearer" : "Bearer error=\"invalid_token\"";
2023-02-18 08:52:17 +01:00
try
{
var localizer = context.HttpContext.RequestServices.GetRequiredService<IStringLocalizer<GenericRes>>();
var webResult = new WebResult().Invalidate(localizer["Unauthorized."], StatusCodes.Status401Unauthorized);
2023-02-18 08:52:17 +01:00
context.Response.ContentType = contentType;
await context.Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(webResult)));
}
catch (Exception ex)
{
_logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<JwtEvents>>();
2026-10-03 10:46:20 +02:00
_logger.LogError(ex, "Error at Challenge()");
2023-02-18 08:52:17 +01:00
}
}
public override async Task Forbidden(ForbiddenContext context)
{
try
{
var localizer = context.HttpContext.RequestServices.GetRequiredService<IStringLocalizer<GenericRes>>();
var webResult = new WebResult().Invalidate(localizer["Forbidden."], StatusCodes.Status403Forbidden);
2023-02-18 08:52:17 +01:00
context.Response.ContentType = contentType;
await context.Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(webResult)));
}
catch (Exception ex)
{
_logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<JwtEvents>>();
2026-10-03 10:46:20 +02:00
_logger.LogError(ex, "Error at Forbidden()");
2023-02-18 08:52:17 +01:00
}
}
}
}