1
votes

We've been facing an issue when downloading a media item in our Sitecore solution. We want to authenticate the user downloading the media. If the user doesn't have access to the file, we need to redirect that user/cancel download.

The thing that decides the redirect is the meta-data on that media item (a field with ID).

We made a module:

<add type="Lib.CustomMediaRequestSessionModule, Lib" name="CustomMediaRequestSessionModule" />

The code:

public class CustomMediaRequestSessionModule : IHttpModule 
{
    public void Init(HttpApplication application)
    {
        application.BeginRequest += Application_BeginRequest;
    }

    private void Application_BeginRequest(object source, EventArgs e)
    {
        var application = (HttpApplication)source;
        var currentContext = HttpContext.Current;

        if (currentContext.Request.Url.ToString().ToLower().Contains("/~/media/"))
        {
            //Here we want to authenticate the user
        }
    }

    public void Dispose()
    {
    }
}

The only information we get from the request is the path to the file. "/~/media/path/to/file.doc".

Is there another way to get more information from the media item? Is there a better approach for doing the same action in Sitecore?

1

1 Answers

4
votes

You can use MediaManager.ParseMediaRequest method to get media item:

MediaRequest request = MediaManager.ParseMediaRequest(HttpContext.Current.Request);

if (request == null)
{
    return false;
}

Media media = MediaManager.GetMedia(request.MediaUri);

There is a nice blog post explaining how you can restrict media items in Sitecore here Restricting access to Sitecore Media Items