Using Umbraco 9 I need to
- Intercept all media requests
- Evaluate if a member is logged in
- If so, pass along the media requested, if not send a 401 status code.
So far I have attempted creating a middleware to do this but I am having an issue in that I can’t accurately detect media requests and also, it looks like I can’t inject the member manager as I think it’s too early in the lifecycle of the app. Any thoughts on how to achieve this would be great.
My Middleware class:
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using Umbraco.Cms.Core.Security;
namespace Ninepoint.Core.Middlewares
{
public class AuthorizedMediaAccess
{
private readonly RequestDelegate _next;
public AuthorizedMediaAccess(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, IMemberManager memberManager)
{
//If its not media, move on...
if (!context.Request.Path.StartsWithSegments("/media"))
{
await _next(context);
}
// Don't return a 401 response if the user is already authenticated.
//if (context.User.Identities.Any(IdentityExtensions => IdentityExtensions.IsAuthenticated))
if (memberManager.IsLoggedIn())
{
await _next(context);
}
// Stop processing the request and return a 401 response.
context.Response.StatusCode = 401;
}
}
}
It is being called in startup.cs here in the “WithMiddleWare” method:
app.UseUmbraco()
.WithMiddleware(u =>
{
u.UseBackOffice();
u.UseWebsite();
u.AppBuilder.UseMiddleware<AuthorizedMediaAccess>();
})
This is a companion discussion topic for the original entry at https://our.umbraco.com/forum/108979-intercept-all-media-requests