49 lines
1.8 KiB
C#
49 lines
1.8 KiB
C#
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.Extensions.Localization;
|
|
|
|
using PrivaPub.ClientModels;
|
|
using PrivaPub.Resources;
|
|
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
|
|
namespace PrivaPub.Services
|
|
{
|
|
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()");
|
|
}
|
|
}
|
|
}
|
|
} |