SocialPub/PrivaPub/Services/JwtEvents.cs

49 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";
public override async Task AuthenticationFailed(AuthenticationFailedContext context)
{
try
{
var localizer = context.HttpContext.RequestServices.GetRequiredService<IStringLocalizer<GenericRes>>();
var webResult = new WebResult().Invalidate(localizer["Unauthorized: {0}", context.Exception], StatusCodes.Status401Unauthorized);
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>>();
_logger.LogError(ex, "Error at AuthenticationFailed()");
}
}
public override async Task Forbidden(ForbiddenContext context)
{
try
{
var localizer = context.HttpContext.RequestServices.GetRequiredService<IStringLocalizer<GenericRes>>();
var webResult = new WebResult().Invalidate(localizer["Forbidden: {0}", context.Result.None ? "N/A" : context.Result.Failure?.Message ?? "N/A"], StatusCodes.Status403Forbidden);
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>>();
_logger.LogError(ex, "Error at AuthenticationFailed()");
}
}
}
}