0

I need a way to prevent access to files in media items if a user is not authenticated.

If a user is not authenticated he/she should be forced to redirect to login Page. If a user is authenticated then we should let the user to access the media item file , like we should handover the request to sitecore.

Also Help me on changing the configuration settings to override the existing mediarequesthandler.

1
  • 1
    Have you tried setting security on the media items?
    – Richard Seal
    Commented May 5, 2022 at 15:43

1 Answer 1

1

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>
2
  • Hi @rvsure , Thanks for the detailed solution. I have implemented the same , but the problem I am facing now is if I directly hit the media URL without any prior sessions opened in browser , I am able to redirect to login page , But once I login & logout to my website & try hitting the same url , I am able to download the media file , without hitting the custom handler method.
    – Harish
    Commented May 6, 2022 at 12:30
  • @Harish Media requests gets cached on the server side (and on the browser, load balancer or CDN depending on your setup). The second time you try the same media link it is served from one of the caches.
    – rvsure
    Commented May 8, 2022 at 22:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.