JSS and OKTA: Blog 1 – Login via External OKTA Form

This blog post is based on the OKTA samples @ https://developer.okta.com/quickstart-fragments/angular/default-example/

The OKTA samples makes use of the OKTA Angular SDK and allows you to set up a development OKTA cloud instance for testing the code.

For this blog I have integrated the OKTA example into the Angular JSS starter repository to for a new repository to accompany this blog. https://github.com/TomTyack/jssokta

This repository contains a working example that I will now run through in the rest of this blog. All you need to do is sign up for your own developer sandbox (OKTA) instance using a dummy user and test it out.


Overview

Firstly lets have a quick run through of the changes we made to the original examples in order to integrate them with the angular JSS application.

  1. OKTA configuration settings
  2. Provide the Login and Logout Buttons
  3. Create the Callback Handler
    • The callback handles integration in JSS takes place inside: src\app\routing\routing.module.ts
    • JSS Example: https://github.com/TomTyack/jssokta/blob/master/JSS/src/app/routing/routing.module.ts
    • In this case I made the route: /implicitcallback
    • Importantly the route must be added at the top of the list so that JSS routing doesn’t hijack the route before our OKTA module gets a chance. I spent a little while scratching my head over this one when I originally added it the bottom of the route config.
  4. Update your NgModule
    • This requires a little bit of adjustment from the original example.
    • Module integration is done via: src\app\app.module.ts
  5. Use the Access Token

Demo Video

To show you a video of this JSS example in action take a quick gander at the following video:

Note: In the video I started off the demo by running in Disconnected mode with localhost. Surprisingly this worked and it redirected back to the connected app domain. In reality a better test would have been to start on the same domain in integrated mode. I’m not sure that you could run this test end to end in disconnected.

Demo Installation

  1. Clone the Repository
  2. Sign up for an OKTA developer account
    • https://developer.okta.com/signup/
    • When it asks you what sort of application you want just click “Do this later”.
    • Confirm your email address and fill out the security questions and change your temporary password.
  3. In the top navigation withing the OKTA Dashboard
  4. Back in the JSS OKTA Repository (open it in VS Code or your editor of choice)
    • From the command line run: npm install
    • Open the file: jss-okta-config.json (in the root of the JSS Application)
      • issuer: Swtich out “INSERT-OKTA-ID” with the relevant ID from the same domain your viewing the OKTA portal in.
      • redirectUri: Replace ‘jssokta’ with ‘jss.okta.portal’ or whichever domain you set.
      • clientId: Found on the application > General tab. About 20 characters long.
  5. IIS
    • OKTA requires us to be running a domain with https, as such it makes it difficult to test this out in Disconnected mode.
    • Setup a Sitecore instance and make sure JSS is installed.
    • Add your new domain to the local hosts file and make sure its mapped to 127.0.0.1
    • Add the new domain to your Sitecore instance in IIS and make sure it capable of HTTPS. Use the developer certificate as a default.
  6. Back in the JSS OKTA Repository
    • Got to sitecore\config\JSSOkta.config
      • hostName: jss.okta.portal
    • From the command line run: JSS Deploy app
      • run through the setup as you would any JSS application so that it would connect with your Sitecore instance.
      • Sample config from my tests: See scjssconfig.json at the bottom of this blog
    • From the command line run: JSS Deploy config
    • From the command line run (again): JSS Deploy app -c -d
  7. Test out the deployed application:
    • Navigate to your domain: example: https://jss.okta.portal/ (must have SSL)
    • If prompted about the SSL security warning proceed and ignore. “Proceed to jss.okta.portal (unsafe)”
    • undefined
    • Click on the “Login” link in the navigation
    • Login to OKTA (if not already) using the details you registered with.
    • You should arrive back on the profile page
    • undefined
    • Success!! hopefully 🙂
    • Inside the OKTA Dashboard is a handy log that shows all login activity. This is a great way to see what is going on. Screenshot shown at the bottom.
      • undefined

Summary

That concludes the run through of how to integrating the OKTA Angular SDK in Sitecore JSS. OKTA is a leader in user authentication management and having the ability to integrate into our JSS applications is an exciting prospect. I hope this example is of use to you and your teams if your considering the same technology mix.


OKTA Setup Screenshots and Sample Config

I have included screenshots of all my OKTA settings below. As I know this can be difficult to diagnose at times.


scjssconfig.json

{
  "sitecore": {
    "instancePath": "C:\\inetpub\\wwwroot\\test.dev.local",
    "apiKey": "{FB95B118-E04F-4D5B-9465-01AE804A2F5A}",
    "deploySecret": "r6bnvuhv13beudhix1lxnej2ci38u0i6kxhnpy22i6ps",
    "deployUrl": "http://jss.okta.portal/sitecore/api/jss/import",
    "layoutServiceHost": "https://jss.okta.portal"
  }
}

Introduce YML Linting to your JSS Apps

Intro: This post shares how and why you might like to introduce a YML linter into the build process for your next Sitecore JSS project. Particularly if you are relying on the YML import process when building a new application. Shout out to David Huby (Solutions Architect) for introducing team Aceik to yaml-lint.

Why would you want to do this on a JSS project?

When running the JSS application and testing latest changes, we sometimes discovered some strange behaviour with dictionary items, or a page might not load properly.

A 404 page displayed after an invalid YML change was made

This can be caused by a small (incorrect) change in YML breaking individual routes. For example, lets say you have an incorrect tab or character in the wrong place. The YML syntax requires correct spacing and line returns to be valid but this is not always so obvious when done incorrectly. Sometimes only after you run the JSS application and test out the changes do you discover some strange behaviours or the page not loading properly.

To avoid this we found it handy to introduce a YML linter into the JSS build process. This solves the issue of someone making a small change to the YML files and breaking individual routes.

Here are the steps needed to introduce a YML linter into a node-based JSS project:

  1. Install yaml-lint (https://www.npmjs.com/package/yaml-lint)
  2. In the application root create the file .yaml-lint.json
  3. Update the package.json
    • Create a new script entry called yamllint
      • “yamllint”: “node ./scripts/yaml-lint.js”
    • Update the script called ‘build’
      • “build”: “npm-run-all yamllint –serial bootstrap:connected build:client build:server”,
  4. Download the following scripts file and place it in the /scripts folder
    1. https://github.com/TomTyack/jss/blob/feature/YAML-Linter/samples/react/scripts/yaml-lint.js

You can also see the pull request with the above changes at:

https://github.com/Sitecore/jss/pull/385/files

Demo

Accessing the JSS Dictionary in C#

This is a quick post to guide developers through gaining access to the JSS Dictionary in the backend C# code.

Why would you want to be able to do this?

The reason we originally had to do this was that our JSS Angular application had editable content from the dictionary that we also wanted to access in C#. In our particular case, it was to inject the content into an email template that would be sent to the user. To save duplicating content it made sense for both the front end and C# to have access to the same dictionary.

Where do we start?

The following assumes you have a Sitecore instance with JSS installed and a JSS application you are working on. Grab your favourite de-compilation tool (I use ILSpy) and locate the following DLL in the bin folder of your running Sitecore instance:

Sitecore.JavaScriptServices.Globalization.dll

Once you have that open in ILSpy you want to have a search for DictionaryServiceController

public class DictionaryServiceController : ApiController

The following method is what we want to use in our C# code:

public DictionaryServiceResult GetDictionary(string appName, string language)

It takes the unique application name (that belongs to your application) and the language (“en”) as a parameter. As a result, you will get back a dictionary object that you can use to lookup up your content.

This is the Controller that would normally be called via an API on the front end. So how do we call it from normal C# service for instance?

Firstly, the controller has a constructor that has three parameters that are injected via DI (Dependency Injection).

IConfigurationResolver configurationResolver, 
BaseLanguageManager languageManager, 
IApplicationDictionaryReader appDictionaryReader

Using ILSpy once again you can find that the above three parameters are all set up in the DI container via RegisterDependencies.cs in various JSS assemblies. The Controller itself is already registered in the DI Container as well, which is very handy.

If you have a look at showconfig.aspx in the admin tools you can see that a lot of the dependencies are registered via RegisterDependencies.cs

For example:

<configurator type="Sitecore.JavaScriptServices.AppServices.RegisterDependencies, Sitecore.JavaScriptServices.AppServices" patch:source="Sitecore.JavaScriptServices.AppServices.config"/>

Dependency injection is a whole other topic so I will leave that to your personal preference as to how you achieve it. For the purposes of the following complete code example, I have used the Services Attribute style setup. If you want to keep consistency with Sitecore you could also setup via the RegisterDependencies.cs class of your own and use a patch file to kick it off.


Example Service:

using Sitecore.Foundation.DependencyInjection; // Borrowed from habitat
using Sitecore.Diagnostics;
using Sitecore.JavaScriptServices.Globalization.Controllers;

namespace Sitecore.Foundation.JSS.Services
{
    public interface ITranslationService
    {
        string TranslateKey(string key);
    }

    [Service(typeof(ITranslationService), Lifetime = Lifetime.Transient)] 
    public class TranslationService : ITranslationService
    {
        private readonly DictionaryServiceController _controller;
        
        public TranslationService(DictionaryServiceController controller)
        {
            this._controller = controller;
        }

        public string TranslateKey(string key)
        {
            var dictionary = GetDictionary();
            if (dictionary.phrases.ContainsKey(key))
                return dictionary.phrases[key];
            Log.Error("Dictionary key {key} not found", this);
            return string.Empty;
        }

        private DictionaryServiceResult GetDictionary(string appName = "myAppName", string language = "en")
        {
           return _controller.GetDictionary(appName, "en");
        }
    }
}

Above is a simple service that can be used from just about anywhere in your C# code.

Simply change the appName and language as required to access the correct JSS dictionary. Also, remember to publish your app dictionary to the web database or you may get no results.


There we have it, accessing the JSS dictionary from C# in a nutshell. I hope this helps some other folks get this done quickly on JSS builds.