Habitat Demo Group and Visual Studio 2017

Recently I had the privilege of attending a Sitecore Helix training. I’ve been using Visual Studio 2017 for a while now and had no trouble getting the Habitat solution running, all I had to do was update the buildToolsVersion to 15.0 in the gulp-config.js file and everything worked as expected.

Getting the Demo.Group solution running was a little bit harder. This solution is necessary for these exercises. There is no buildToolsVersion property in the gulp-config.js, instead version 14.0 is hardcoded in the gulpfile.js. I added the property in the gulp-config.js and used this property in the gulpfile.js instead of 14.0.

After this change it got a little further but still was not able to successfully run all the Gulp tasks. This time it gave me this error: “throw new PluginError(constants.PLUGIN_NAME, ‘No MSBuild Version was supplied!’); ” This stackexchange post has the answer to this issue. The Sitecore.Demo.Group solution uses an old version of gulp-msbuild, updating this to version 0.4.4 in the package.json resolved all remaining issues.

 

Sitecore use OAuth2 login with OWIN

As an experiment I wanted to see if it would be possible to use the social logins such as google with Sitecore using a similar approach as a plain MVC app. More details around doing this without Sitecore can be found here Notice that the code used in ASP .NET MVC relies on OWIN authentication middleware and ASP .NET Identity. This makes sense in ASP .NET, but we’ll have to reconsider this when integrating with Sitecore. A similar post using OWIN in Sitecore using Federated Authentication can be found here.

Sitecore and OWIN

Using OWIN with Sitecore makes sense, it is certainly possible to not use OWIN and rely on a custom implementation instead. There are some blog posts as well that will help you get started.

Given the security implications of getting a custom implementation slightly incorrect, it is highly recommended to use a proven solution like the OWIN middleware.

Additionally OWIN is widely used in regular ASP .NET applications. OWIN comes as a nuget package which makes it straightforward to update and take advantage of new features.

Sitecore and ASP .NET Identity

Using Sitecore with ASP .NET Identity does not make sense to me as Sitecore still uses ASP .NET membership. Using ASP .NET Identity would add another component that I could not see a use or benefit for, but please let me know in case anyone does. Some code in this post is from this post which describes how to use OWIN without ASP .NET Identity in ASP .NET MVC.

Configuring OWIN Middleware

Below code configures the OWIN middleware to use google authentication:

using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;

namespace SitecoreOwinGoogle
{
    public partial class Startup
    {
        private void ConfigureAuth(IAppBuilder app)
        {
            var cookieOptions = new CookieAuthenticationOptions
            {
                LoginPath = new PathString("/Login")
            };

            app.UseCookieAuthentication(cookieOptions);

            app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType);

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
            {
                ClientId = "your client id",
                ClientSecret = "your client secret"
            });
        }
    }
}

Notice in the usings that only OWIN is referenced, there are no ASP .NET Identity referenes added. ClientId and ClientSecret can be obtained from from Google Developers Console Never store passwords and other sensitive data in source code, for best practices see here

Login Through Google

In the OWIN middleware /Login is set as the login path. This can be set to a different path as well as long as there is code running when that path is hit to handle the login. I added a controller rendering here to transfer control to google:

public ActionResult Login(string returnUrl)
{
    return new ChallengeResult("Google",
      string.Format("/Login/ExternalLoginCallback?ReturnUrl={0}", returnUrl));
}

The ExternalLoginCallback will redirect the user to secure page that he was trying to navigate to before the OWIN middleware kicked in. It is important to run this code in the path specified in the redirectUri parameter on the ChallengeResult constructor, in this case “/Login/ExternalLoginCallback”.  Again I’m using a controller rendering for this.

public ActionResult ExternalLoginCallback(string returnUrl)
{
    return new RedirectResult(returnUrl);
}

I have used the same ChallengeResult class as ASP .NET MVC:

// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";

internal class ChallengeResult : HttpUnauthorizedResult
{
    public ChallengeResult(string provider, string redirectUri)
        : this(provider, redirectUri, null)
    {
    }

    public ChallengeResult(string provider, string redirectUri, string userId)
    {
        LoginProvider = provider;
        RedirectUri = redirectUri;
        UserId = userId;
    }

    public string LoginProvider { get; set; }
    public string RedirectUri { get; set; }
    public string UserId { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
        if (UserId != null)
        {
            properties.Dictionary[XsrfKey] = UserId;
        }
        context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
    }
}

Redirect back to Sitecore

After google completed validating the user it will redirect back to Sitecore. By default OWIN expects this at /signin-google. Here OWIN will set the cookie used for the CookieAuthentication. Make sure to configure this page as an authorized redirect URI in google’s console.

Sitecore will try to handle the request which is made to /signin-google, Sitecore should not touch this request and let OWIN handle it. The easiest way to achieve this is by adding this page to the IgnoreUrlPrefixes setting. From there OWIN will call the callback URL specified in the ChallengeResult and this will redirect back to page that is secured.

Securing pages

That is all for the OWIN and OAuth code. Now that this is in place a controller action method can be decorated with the Authorize attribute to trigger the authentication flow. Below diagram shows the end-to-end flow:

Authentication flow

Further considerations

As mentioned before this blog post is a start in using OWIN with OAuth2 in Sitecore. However there are many other items to explore:

  • Multisite support: perhaps you have a multisite solution and some sites need social logins and other sites need a different login method. OWIN supports branching the pipeline to allow for different configurations based on a condition e.g. hostname
  • Support different social provider: this blog post only works with google, but OWIN supports several different logins like Facebook, Twitter, Linkedin or Microsoft.
  • Logoff: this post only covers login, but it should be fairly straightforward to implement logoff in a similar fashion.
  • Sitecore Virtual Users: the authentication in this post is basic, either you are successfully logged in from google or you are not. Most real world applications are more complicated and different users have different permissions. In these cases it can be helpful to create a Sitecore virtual user and assign Sitecore roles.
  • OAuth2 scope: there is a scope parameter which supports retrieving additional information about the user from google. The users will have to accept this first on the consent screen when they use google’s system to log in.

Summary

This post showed how to set up OWIN with Sitecore and OAuth2. Using OWIN significantly simplified working with OAuth2 and google. There are a number of additional considerations that must be taken into account before using this in a production scenario.

Sitecore namespace issues

Since I ran into this silly issue a couple of times I decided to dig into it a little bit and write a post about it. As developers we like to structure our solutions and projects by applying consistent naming conventions. Most Sitecore projects use a naming convention like this prefix.Sitecore.description. Usually the prefix is something like a company name or a brand name, and the description is something that describes the project’s role in the solution. There can also be multiple prefixes and descriptions separated by a period. Looking at Habitat an example of description could be Feature.Accounts.

A popular approach is to keep project names, assembly names, folder structure and namespaces all in sync for clarity. If you go with this approach you will end up with a namespace like MyBrand.Sitecore.Features.Accounts. This is where things can get a little messy because “Sitecore” is in the namespace and this can conflict with references to Sitecore DLL’s. Consider below piece of code:

namespace MyBrand.Sitecore.Features.Accounts
{
    using Sitecore;

    public class Helper
    {
        public string ReturnCurrentItemName()
        {
            var item = Sitecore.Context.Item;

            return item.Name;
        }
    }
}

This code will create below compile error:

Error CS0234 The type or namespace name ‘Context’ does not exist in the namespace ‘MyBrand.Sitecore’ (are you missing an assembly reference?)

Problem

The problem here is how namespace resolution works for nested namespaces, more details can be found in the C# language specification here. As the compile error suggests it is looking for the Context object in our class instead of in Sitecore in the root scope. The good news is that there are at least 3 different ways to solve this:

1. Avoid using anything before “Sitecore” in namespace

The same code will compile just fine when “Sitecore” is the first part of the namespace, see line 1. This is the easiest solution if changing the namespace is not a problem.

namespace Sitecore.Features.Accounts
{
    using Sitecore;

    public class Helper
    {
        public string ReturnCurrentItemName()
        {
            var item = Sitecore.Context.Item;

            return item.Name;
        }
    }
}

2. Use namespace alias

This is my least favorite way to solve this but it also seems to be the most common solution. The Sitecore namespace from the Sitecore DLL can be declared as an alias and then used to reference:

using RealSitecore = Sitecore;

namespace MyBrand.Sitecore.Features.Accounts
{
    public class Helper
    {
        public string ReturnCurrentItemName()
        {
            var item = RealSitecore.Context.Item;

            return item.Name;
        }
    }
}

3. Use global namespace alias

Instead of making up a random name for Sitecore as in the last solution, it feels a lot cleaner to use the global namespace alias to tell the compiler to look in the global namespace instead:

namespace MyBrand.Sitecore.Features.Accounts
{
    using Sitecore;

    public class Helper
    {
        public string ReturnCurrentItemName()
        {
            var item = global::Sitecore.Context.Item;

            return item.Name;
        }
    }
}

Summary

As long as there is no problem changing the namespace to start with “Sitecore” then option 1 is the best choice. If for whatever reason that is not an option then go with using the global namespace alias as described in option 3.