You can override the out of the box media handler with your own and do some custom logic to check if the user is authenticated. Your custom media handler should inherit from Sitecore.Resources.Media.MediaRequestHandler or Sitecore.XA.Foundation.MediaRequestHandler.MediaRequestHandler if using SXA. You should override the DoProcessRequest method and add your custom logic to check if user is authenticated.
Here is an example custom Media Request Handler
using System.Web;
using Sitecore.Resources.Media;
namespace MyCustomCode.Handlers
{
public class MediaRequestHandler : Sitecore.Resources.Media.MediaRequestHandler
{
protected override bool DoProcessRequest(HttpContext context, MediaRequest request, Media media)
{
// Do your authentication and redirect logic here
return base.DoProcessRequest(context, request, media);
}
}
}
Once you have your custom media request handler you need to override the default setting in web.config using Web.config transforms
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.webServer>
<handlers>
<add verb="*" path="sitecore_media.ashx" type="MyCustomCode.Handlers.MediaRequestHandler, MyCustomCode" name="Sitecore.MediaRequestHandler" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</handlers>
</system.webServer>
</configuration>