TackleMcClean 🏅
08/31/2023, 3:05 PMD_Inventor
08/31/2023, 3:26 PMTackleMcClean 🏅
08/31/2023, 5:11 PMD_Inventor
08/31/2023, 5:14 PMD_Inventor
08/31/2023, 5:15 PMcsharp
public class AutoLoginMiddleware
{
private readonly RequestDelegate _next;
private readonly IRuntimeState _runtimeState;
public AutoLoginMiddleware(RequestDelegate next, IRuntimeState runtimeState)
{
_next = next;
_runtimeState = runtimeState;
}
public async Task InvokeAsync(HttpContext httpContext, IBackOfficeSignInManager signInManager, IBackOfficeUserManager backOfficeUserManager, IUmbracoContextAccessor umbracoContextAccessor)
{
// ignore this middleware as long as umbraco hasn't been initialised yet
if (_runtimeState.Level < RuntimeLevel.Run)
{
await _next(httpContext);
return;
}
// if PublishedRequest is null, request is not from frontend
if (!IsAuthenticated(httpContext) && IsBackofficeRequest(umbracoContextAccessor) && RequestIsLocal(httpContext))
{
// login default user
var user = await backOfficeUserManager.FindByIdAsync(Constants.Security.SuperUserIdAsString);
await signInManager.SignInAsync(user, true);
}
await _next(httpContext);
}
private static bool IsBackofficeRequest(IUmbracoContextAccessor umbracoContextAccessor)
{
return umbracoContextAccessor.TryGetUmbracoContext(out var umbracoContext) && umbracoContext.PublishedRequest is null;
}
private static bool IsAuthenticated(HttpContext httpContext)
{
return httpContext.User.Identity?.IsAuthenticated ?? false;
}
private static bool RequestIsLocal(HttpContext httpContext)
{
var remoteAddress = httpContext.Connection.RemoteIpAddress?.ToString();
// The requester may automatically sign in if they connect from a local ip or a local network ip
return httpContext.Request.IsLocal()
|| (remoteAddress != null && remoteAddress.StartsWith("192.168", StringComparison.OrdinalIgnoreCase));
}
}
TackleMcClean 🏅
08/31/2023, 8:07 PM