Wednesday 10 May 2023

Locking down requests from Sitecore to Head

For those coming from on-prem or PaaS the leap to the exciting new world of Sitecore SaaS can be quite daunting, with many new factors and considerations - not the least of which is security (which should always be front-of-mind).  Your dev teams may be busy brushing up on containers and headless, but infra teams will be more concerned with integrating with XM Cloud, most notably with the Head.

Most of you will (hopefully) already be familiar with a couple of the ways that communication between the Head and Sitecore can be secured:

  1. A Sitecore API key - allows you to lock down your API calls to the Layout Service and GraphQL endpoints, as well as impersonate users.
  2. The JSS Editing Secret - used as a shared key to ensure the app and Sitecore Editor are the only parties authorized to talk to one another while in Experience Editor mode.

But what if you want a bit of extra security? Say you have a WAF (something to that effect) which only allows certain headers? As always, Sitecore is nice and extensible:

The class making the HTTP call to your Head app is Sitecore.JavaScriptServices.ViewEngine.Http.RenderEngine and it creates a HttpClient to make the requests using Sitecore.JavaScriptServices.ViewEngine.Http.HttpClientFactory which has the following method:

public IHttpClient Create(HttpRenderEngineOptions options)
{
	Assert.IsNotNull(options, "options");
	return new TimeoutCapableWebClient(options.RequestTimeoutMs)
	{
		Encoding = Encoding.UTF8,
		Headers = { [HttpRequestHeader.ContentType] = "application/json" }
	};
}

This HttpClientFactory is created through DI, so you can just inject your own and add your own headers! Too easy!

Thursday 4 May 2023

Sitecore Headless Forms - Hidden Field Using Query Value

This one goes out to @AJS on Sitecore slack who asked how they could implement the query string provider in Sitecore Forms (headless/JSS).

Firstly, make sure you add the QueryStringProvider from Sitecore Forms Extensions, as well adding the required Sitecore item(s) to your instance.

Once that's done see the Sitecore documentation on adding a React/Next.JS form to your headless app.

Finally you're ready to implement a custom field factory (see my previous post) with a custom hidden element, setting the value based on the value from the query string:

Enjoy!