Sunday, 25 October 2015

Get site name of Current item in Sitecore

Below code shows how to get the site name of current context item in the multi site environment of Sitecore setup

        public static string GetSiteName(this Item item)
        {
            var siteInfoList = Sitecore.Configuration.Factory.GetSiteInfoList();
            var siteInfo = siteInfoList.FirstOrDefault(
                info => item.Paths.FullPath.ToLower().StartsWith(info.RootPath.ToLower()));

            return siteInfo.Name;
        }

Wednesday, 21 October 2015

HTTPS redirection and Sitecore



This blog explains different methods to redirect the Site/Pages in HTTPS to secure the page.
Note: Most of the methods are not Sitecore specific but related IIS rewrite module.
For more details on IIS rewrite module refer the below URL:


1   Browse entire site in HTTPS
  
If you want to force the user to browse the site only in HTTPS, then the best way is to write the IIS rewrite rule to redirect the site to https protocol.


Sample rewrite config looks like below:

1.       If IIS website contains only one site or all the sites mentioned in binding need to browse in https, then follow the similar config mentioned below:

<rule name="Force HTTPS" enabled="true">
  <match url="(.*)" />
    <conditions logicalGrouping="MatchAll">
      <add input="{HTTPS}" pattern="off" />
    </conditions>
   <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" />
</rule>

2.       If IIS website contains multiple site (multiple domains in bindings) and only few domains need to force to HTTPS, then add the HOST condition. EX:
<rule name="Force HTTPS" enabled="true">
  <match url="(.*)" />
<conditions logicalGrouping="MatchAll">
  <add input="{HTTP_HOST}" pattern="mysite.com.au" />
  <add input="{HTTPS}" pattern="off" />
</conditions>
   <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" />
</rule>

 
2. Browse selected pages in HTTPS
 2.1 Using IIS rewrite rules

If only few pages in the site need to be redirected in HTTPS, then add the URL condition to match the URLs, ex:

<rule name="Force HTTPS" enabled="true">
  <match url="(.*)" />
<conditions logicalGrouping="MatchAll">
  <add input="{HTTP_HOST}" pattern="mysite.com.au" />
  <add input="{HTTP_URL}" pattern="/test-page*" />
  <add input="{HTTPS}" pattern="off" />
</conditions>
   <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" />
</rule>

Ex: Here all the URLs starts with 'test-page' will redirect to https.

Updating the configs frequently in production for the new URLs may be difficult.
If it is a Sitecore site, we can then manage this by adding the “HttpRequest” Pipeline and by mentioning in the content whether or not the page need to browse in HTTPS


2.2 Using Sitecore Pipeline

Sitecore will provide the pipeline help to redirect the current URLs. Use HttpRequestProcessor in the httpRequestBegin pipeline.


-          Create a one Class library project (ex: Redirect.HttpsRedirection)
-          Create a class and inherit from HttpRequestProcessor
Ex:
public class SecureRedirection : HttpRequestProcessor
    {
        public override void Process(HttpRequestArgs args)
        {
            Item item = Context.Item;
            string uri = string.Empty;

            try
            {
                if (item == null
                    || args.Context.Request.Url.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.InvariantCultureIgnoreCase))
                    return;

                if (item.Fields["IsSecured"] != null)
                {
                    CheckboxField secureField = (CheckboxField)item.Fields["IsSecured"];

                    if (secureField != null && secureField.Checked)
                    {
                        uri = args.Context.Request.Url.AbsoluteUri;

                        if (!uri.StartsWith(Uri.UriSchemeHttp, StringComparison.InvariantCultureIgnoreCase))
                            return;

                        args.Context.Response.Redirect(uri.Replace("http://", "https://"), true);
                    }
                }
            }
            catch(Exception ex)
            {
                Log.Error(ex.Message, this);
            }
        }
    }

-          Create one config file and add httpRequestBegin pipeline
Ex: Redirect.SecureRedirect.config
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <httpRequestBegin>
        <processor patch:after="*[@type='Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel']" type="Redirect.HttpsRedirection.SecureRedirection, Redirect.HttpsRedirection" />
      </httpRequestBegin>
    </pipelines>
  </sitecore>
</configuration>

Now create a template to add the “IsSecured field to your page, inherit this template wherever you required

 After inheriting the above template into your page template ypu will get a option to select whether or not the page need to be forced to browse in https.



Thanks,
Sharath