Fixes 401 Unauthorized API responses being incorrectly cached

This commit is contained in:
BinaryAlley committed 2024-12-25 18:34:49 +02:00
1 parent f246f0bf75
commit d6af519e17
37 files changed
+298 -174

No files matched your search

@@ -8,7 +8,6 @@ using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
@@ -44,6 +43,8 @@ public class ApiHttpClient : IApiHttpClient
ServerConfigurationModel serverConfigurationModel = serverConfigurationOptions.Value;
httpClient.BaseAddress = new Uri($"{serverConfigurationModel.BaseAddress}:{serverConfigurationModel.Port}/api/v{serverConfigurationModel.ApiVersion}/");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_jsonOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
@@ -4,8 +4,6 @@ using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Models.UsersManagement;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Threading.Tasks;
#endregion
@@ -17,17 +15,14 @@ namespace Lumina.Presentation.Web.Common.Authorization;
public class InitializationHandler : AuthorizationHandler<InitializationRequirement>
{
private readonly IApiHttpClient _apiHttpClient;
private readonly IMemoryCache _cache;
/// <summary>
/// Initializes a new instance of the <see cref="InitializationHandler"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected HTTP typed client for interactions with the API.</param>
/// <param name="cache">Cache for storing the initialization status.</param>
public InitializationHandler(IApiHttpClient apiHttpClient, IMemoryCache cache)
public InitializationHandler(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
_cache = cache;
}
/// <summary>
@@ -3,7 +3,9 @@ using FluentValidation;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Filters.ActionFilters;
using Lumina.Presentation.Web.Common.Filters.AuthorizationFilters;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.MiddlewareFilters;
using Lumina.Presentation.Web.Common.Models.Authorization;
using Lumina.Presentation.Web.Common.Security;
@@ -25,6 +27,7 @@ using Polly.Wrap;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json.Serialization;
@@ -48,8 +51,8 @@ public static class PresentationWebLayerServices
{
services.AddControllersWithViews(mvcOptions =>
{
//mvcOptions.Filters.Add<ApiExceptionFilter>();
mvcOptions.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipeline))); // add localization middleware filter
mvcOptions.Filters.Add<StoreLastViewFilter>();
})
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization()
@@ -129,34 +132,59 @@ public static class PresentationWebLayerServices
// handle redirects to work with different base paths
OnRedirectToLogin = redirectContext =>
{
string culture = redirectContext.HttpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
// preserve any base path or subdirectory and add return URL
string redirectPath = redirectContext.RedirectUri;
// insert culture into the path
redirectPath = redirectPath.Replace("/auth/login", $"/{culture}/auth/login");
if (redirectContext.Request.PathBase.HasValue)
redirectPath = redirectContext.Request.PathBase + cookieAuthenticationOptions.LoginPath + new QueryString("?returnUrl=") + Uri.EscapeDataString(redirectContext.Request.PathBase + redirectContext.Request.Path);
redirectContext.Response.Redirect(redirectPath);
HttpContext httpContext = redirectContext.HttpContext;
string culture = httpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string? lastDisplayedView = httpContext.Session.GetString(HttpContextItemKeys.LAST_DISPLAYED_VIEW);
// build the login path considering reverse proxy and subfolder scenarios
string? originalHost = httpContext.Request.Headers["X-Forwarded-Host"].FirstOrDefault() ?? httpContext.Request.Host.Value;
string? originalScheme = httpContext.Request.Headers["X-Forwarded-Proto"].FirstOrDefault() ?? httpContext.Request.Scheme;
string? originalPathBase = httpContext.Request.Headers["X-Forwarded-Prefix"].FirstOrDefault() ?? httpContext.Request.PathBase.Value;
string baseUrl = $"{originalScheme}://{originalHost}{originalPathBase}";
string loginPath = $"{baseUrl}/{culture}/auth/login";
if (!string.IsNullOrEmpty(lastDisplayedView))
{
string returnUrl = Uri.EscapeDataString(lastDisplayedView);
redirectContext.RedirectUri = $"{loginPath}?returnUrl={returnUrl}";
}
else
redirectContext.RedirectUri = loginPath;
httpContext.Response.Redirect(redirectContext.RedirectUri);
return Task.CompletedTask;
},
OnRedirectToLogout = redirectContext =>
{
string culture = redirectContext.HttpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string redirectPath = redirectContext.RedirectUri;
redirectPath = redirectPath.Replace("/auth/logout", $"/{culture}/auth/logout");
if (redirectContext.Request.PathBase.HasValue)
redirectPath = redirectContext.Request.PathBase + cookieAuthenticationOptions.LogoutPath;
redirectContext.Response.Redirect(redirectPath);
HttpContext httpContext = redirectContext.HttpContext;
string culture = httpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string? originalHost = httpContext.Request.Headers["X-Forwarded-Host"].FirstOrDefault() ?? httpContext.Request.Host.Value;
string? originalScheme = httpContext.Request.Headers["X-Forwarded-Proto"].FirstOrDefault() ?? httpContext.Request.Scheme;
string? originalPathBase = httpContext.Request.Headers["X-Forwarded-Prefix"].FirstOrDefault() ?? httpContext.Request.PathBase.Value;
string baseUrl = $"{originalScheme}://{originalHost}{originalPathBase}";
string logoutPath = $"{baseUrl}/{culture}/auth/logout";
redirectContext.RedirectUri = logoutPath;
httpContext.Response.Redirect(redirectContext.RedirectUri);
return Task.CompletedTask;
},
OnRedirectToAccessDenied = redirectContext =>
{
string culture = redirectContext.HttpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string redirectPath = redirectContext.RedirectUri;
redirectPath = redirectPath.Replace("/auth/access-denied", $"/{culture}/auth/access-denied");
if (redirectContext.Request.PathBase.HasValue)
redirectPath = redirectContext.Request.PathBase + cookieAuthenticationOptions.AccessDeniedPath;
redirectContext.Response.Redirect(redirectPath);
HttpContext httpContext = redirectContext.HttpContext;
string culture = httpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string? originalHost = httpContext.Request.Headers["X-Forwarded-Host"].FirstOrDefault() ?? httpContext.Request.Host.Value;
string? originalScheme = httpContext.Request.Headers["X-Forwarded-Proto"].FirstOrDefault() ?? httpContext.Request.Scheme;
string? originalPathBase = httpContext.Request.Headers["X-Forwarded-Prefix"].FirstOrDefault() ?? httpContext.Request.PathBase.Value;
string baseUrl = $"{originalScheme}://{originalHost}{originalPathBase}";
string accessDeniedPath = $"{baseUrl}/{culture}/auth/access-denied";
redirectContext.RedirectUri = accessDeniedPath;
httpContext.Response.Redirect(redirectContext.RedirectUri);
return Task.CompletedTask;
}
};
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
#endregion
namespace Lumina.Presentation.Web.Common.Filters.ActionFilters;
/// <summary>
/// Stores the current view path in session, for actions that return ViewResult. This is needed because when JWT expires, user is redirected to Login view, with a returnUrl.
/// This returnUrl needs to be that of the last displayed view, not of the call that triggered the re-authentication request, which can be an API call for data.
/// </summary>
public class StoreLastViewFilter : IActionFilter
{
/// <summary>
/// Executes before the action method is called
/// </summary>
/// <param name="context">The action executing context</param>
public void OnActionExecuting(ActionExecutingContext context)
{
// no action needed before execution
}
/// <summary>
/// Executes after the action method is called
/// </summary>
/// <param name="context">The action executed context containing the action result</param>
public void OnActionExecuted(ActionExecutedContext context)
{
if (context.Result is ViewResult)
{
HttpContext httpContext = context.HttpContext;
if (httpContext.Request.Path != "/en-us/auth/login")
httpContext.Session.SetString(HttpContextItemKeys.LAST_DISPLAYED_VIEW, $"{httpContext.Request.PathBase}{httpContext.Request.Path}{httpContext.Request.QueryString}");
}
}
}
@@ -41,12 +41,13 @@ public class ApiAuthorizationFilter : IAsyncAuthorizationFilter
if (!await _authorizationService.EvaluateAuthorizationAsync(_requirement))
context.Result = new ForbidResult();
}
catch (ApiException ex)
catch (ApiException ex) // TODO: check if it should really catch exceptions here
{
if (ex.HttpStatusCode == System.Net.HttpStatusCode.Unauthorized)
{
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false);
context.HttpContext.Response.Cookies.Delete("Token");
throw;
}
}
}
@@ -7,4 +7,5 @@ public static class HttpContextItemKeys
{
public const string ERRORS = "errors";
public const string PENDING_SUPER_ADMIN_SETUP = "PendingSuperAdminSetup";
public const string LAST_DISPLAYED_VIEW = "LastViewUrl";
}
@@ -80,6 +80,20 @@ public class ExceptionHandlingMiddleware
// handle unauthorized errors by prompting the user to re-login
if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in)
await HandleUnauthorizedAsync(context);
else if (apiException.HttpStatusCode == HttpStatusCode.Forbidden)
{
if (IsApiRequest(context))
{
string errorMessage = BuildErrorMessage(apiException);
await WriteJsonResponseAsync(context, new
{
success = false,
errorMessage
});
}
else
await context.ForbidAsync();
}
else
{
string errorMessage = BuildErrorMessage(apiException);
@@ -97,7 +111,7 @@ public class ExceptionHandlingMiddleware
private async Task HandleUnauthorizedAsync(HttpContext context)
{
// when API JWT tokens expire, the client app is still logged in, so, sign out the user and delete the authentication cookie and token
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false);
context.Response.Cookies.Delete("Token");
if (IsApiRequest(context))
@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Models.Common;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Net;
using System.Net.Http;
@@ -41,15 +40,15 @@ public class CachedAuthorizationHandler : DelegatingHandler
string requestPath = request.RequestUri!.AbsolutePath;
// if it's any endpoint other than the one for the authorization request, fire it away towards the original API service
if (!requestPath.EndsWith(AUTHORIZATION_ENDPOINT, StringComparison.OrdinalIgnoreCase))
return await base.SendAsync(request, cancellationToken);
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
// otherwise, check the hybrid cache to see if there is a cached authorization
CachedResponseModel response = await _hybridCache.GetOrCreateAsync(
AUTHORIZATION_ENDPOINT,
async (cancellationToken) =>
{
// perform the actual API call if cache is empty or expired
HttpResponseMessage result = await base.SendAsync(request, cancellationToken);
string content = await result.Content.ReadAsStringAsync(cancellationToken);
HttpResponseMessage result = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
string content = await result.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
// cache both status code and content
return new CachedResponseModel
{
@@ -63,6 +62,10 @@ public class CachedAuthorizationHandler : DelegatingHandler
},
cancellationToken: cancellationToken
);
// if the API returned 401 Unauthorized (i.e. token expired), DO NOT cache this response - it will be used for authorization endpoints even after successful login,
// resulting in incorrect login redirection cycles!
if (response.StatusCode == HttpStatusCode.Unauthorized)
await _hybridCache.RemoveAsync(AUTHORIZATION_ENDPOINT, cancellationToken).ConfigureAwait(false);
return new HttpResponseMessage(response.StatusCode)
{
Content = new StringContent(response.Content)
@@ -66,8 +66,6 @@ public class UrlService : IUrlService
foreach (PropertyInfo prop in additionalRouteValues.GetType().GetProperties())
routeValues.Add(prop.Name, prop.GetValue(additionalRouteValues));
// create route values based on whether the controller is localized
object values = needsCulture ? new { culture, action } : new { action };
return _linkGenerator.GetUriByAction(httpContext: httpContext, action: action, controller: controller, values: routeValues, scheme: scheme);
return _linkGenerator.GetUriByAction(httpContext: httpContext, action: action, controller: controller, values: routeValues, scheme: scheme);
}
}