Pages

10 April, 2017

Redirect restricted media items with ReturnURL

Sitecore can redirect the user to login page if the requested item is restricted for anonymous users. This can be done in the Site configuration. 
requireLogin="true"
loginPage="/redirectpage"
There are two differences in this redirection. For Sitecore item, it will be redirected with returnURL querystring with source url. For Media item, querystring is not added. In one of the project, we had to handle the redirection based on the source url for the Sitecore Media items. To achieve this, MediaRequestHandler can be modified and it will return a query parameter with source URL. Please make sure to update the <handler> with the new class and assembly name. 

  protected override bool DoProcessRequest(HttpContext context) {
	Assert.ArgumentNotNull(context, "context");
	MediaRequest mediaRequest = MediaManager.ParseMediaRequest(context.Request);
	if (mediaRequest == null) {
		return false;
	}
	Media media = MediaManager.GetMedia(mediaRequest.MediaUri);
	if (media == null) {
		using(new SecurityDisabler()) {
			media = MediaManager.GetMedia(mediaRequest.MediaUri);
		}
		string text;
		if (media == null) {
			text = Sitecore.Configuration.Settings.ItemNotFoundUrl;
		}
		else {
			Assert.IsNotNull(Context.Site, "site");
			text = ((Context.Site.LoginPage != string.Empty) 
                        ? Context.Site.LoginPage: Sitecore.Configuration.Settings.NoAccessUrl);
		}
		//Setup redirect url - Start
		UrlString urlString = new UrlString(text);
		if (string.IsNullOrEmpty(urlString["returnUrl"])) {
			urlString["returnUrl"] = WebUtil.GetRawUrl();
			urlString.Parameters.Remove("item");
			urlString.Parameters.Remove("user");
			urlString.Parameters.Remove("site");
		}
		//Setup redirect url - End
		WebUtil.Redirect(urlString.ToString(), false);

		return true;
	}
	return this.DoProcessRequest(context, mediaRequest, media);
  }
In the web.config, <handler> tag has to be updated with new class and assembly name. 
<add verb="*" path="sitecore_media.ashx" type="CustomHandler.MediaRequestHandler, CustomHandler" 
name="Sitecore.MediaRequestHandler" />

No comments:

Post a Comment

blockquote { margin: 0; } blockquote p { padding: 15px; background: #eee; border-radius: 5px; } blockquote p::before { content: '\201C'; } blockquote p::after { content: '\201D'; }