Tag: Webhooks

Secure Sitecore Webhooks using Microsoft Azure AD B2C

Few months back I was trying to Authorize Sietcore Webhooks using Microsoft Actice Directory B2C and found issue that it wasn’t working.

After creating a support ticket, Sitecore logged this as a bug.

This was resolved and release on 20th Feb 2024.

This blog helps on how to configure MS AD B2C and configure in Sitecore as Client Credential grant to generate an access token so the Event receiver can authorize and process the request.

Note- text highlighted in red is required later to configure in Sitecore.

Reference-

https://doc.sitecore.com/xp/en/developers/103/sitecore-experience-manager/webhook-authentication-types.html

https://developers.sitecore.com/changelog/xm-cloud/1.5.69-base-image-update%3a-resolved-issues

Pre-requisite

You should have your Azure AD B2c tenant. See this link on how to set this – Tutorial – Create an Azure Active Directory B2C tenant | Microsoft Learn

Once configured you see the options to register your app.

Before registering app note down the highlighted. This should be available as the part of Endpoint-

This is Authority URL in Sitecore Webhook.

Step 1 – Register App

Click on New registration

Provide the App registration name and selected supported account types. In this case I have given name – SCXMCWebhook and selected “Accounts in this organizational directory only (SC XM Org only – Single tenant)

Register App and it should show the registered app-

It should also list your newly created app-

Step 2 – Add an Application URI

Click on Application ID URI “Add”link and then “Add a scope”

This should create a URI –

Step 3 – Add a scope

Now create a scope “Add a scope”. Enter scope name, admin consent and description. Ensure you enable the scope.

A new scope isadded . Copy the scope as highlighted –

Step 4 – Create Secrets

Navigate to Overview tab and you should see all the configured details.

Step 5 – Create a Client Credential Grant Authorization in Sitecore

Sitecore Client CredentialMicrosoft AD B2C
Authority URL Microsoft Entra ID OpenID Connect
metadata document. (Check Endpoints)
Client IDApplication (client) ID
(Check Overview tab)
Client SecretClient Secret Value
(Check Certificates & Secrets tab)
Scope
(Append /.default)
Application ID URI
(Check Overview tab)
Header Prefix
(Bearer)
Additional Endpoint Base Addresses
(See Semicolon seperated values below)
Directory (tenant) ID
(Part of the url- Check Overview tab)
e.g.:- 10d**************1b4c

Additional Endpoint Base Addresses

https://login.microsoftonline.com/10d**************1b4c/discovery/v2.0/keys
https://login.microsoftonline.com/110d**************1b4c/oauth2/v2.0/token
https://graph.microsoft.com/oidc/userinfo
https://login.microsoftonline.com/10d**************1b4c/oauth2/v2.0/authorize
https://login.microsoftonline.com/10d**************1b4c/oauth2/v2.0/devicecode
https://login.microsoftonline.com/10d**************1b4c/oauth2/v2.0/logout
https://login.microsoftonline.com/10d**************1b4c/kerberos

Client Credential Grant Authorization Item should look like this-

Please note Additional Endpoint Base Address are Semicolon seperated.

Step 6 – Create a Webhook Handler in Sitecore

Create Webhook handler at this location- /sitecore/system/Webhooks/

Provide the Description, Select the events the webhook should trigger, Add any rules as per your requirements, Ensure to Enable the Webhook, provide the Url the webhook should send the item data, select the newly created Authorization and Selrialization type (JSON).

Step 7 – Save an Item in Sitecore

Update an Item, in this case I updated Home item

You should see the webhook sends the request to defined Url with Access Token, as highlighted below-

Hope this helps to cionfigure MS AD B2C in your Sitecore instance

More reads-

Loading

Automation with Sitecore XM Cloud Webhooks and Zapier

With Zapier you can inspect and create customised workflow in munites without wirting any code. Its a good way to automate any actions required once the webhooks in Sitecore are triggered.

In this blog post will quickly create a workflow in Zapier to send mail when a webhook event is trigerred.

Will take a scenario when a Home page is updated, so that the concern team knows about this change.

This is not a fully customised solution but you can extend this as per your requirements.

Create a Zapier account

Create a Zapier account if you don’t have already. There is free subscription available to try out.

Login to Zapier and create a new Zap

Configure a trigger- Select Webhook by Zappier

When a new zap is created select a Catch Hook event in App & Event section

In the test section it should provide the URL its listening to execute any autmation if applicable.

Test the trigger by copying the s URL and setup the same in your Webhokk Handler in Sitecore XM CLoud or local instance. See this blog post on how to create a webhook handler.

Update content in Home page and Save. This should triggere the webhook and call the Zapier endpoint configured in handler.

Test trigger and should see the request available to this endpoint-

Continue with Selected Record if you are happy with the request-

Apply Filter

We want to send mail only when Home page is changed, so lets apply filter

Configure the filter

Add the condition

Further action will be taken only if Item name is Home. This just an example you can select the list of action available.

Continue and select next action and in this case I selected to send a mail to Gmail

Select the event “Send Mail”

Setup your account.

Setup the action to whom the mail should be sent and other information required for the mail

Continue and Test the Step

Now you should have the Zap configured-

Publish the Zap

Change the name of the Zap and should be available in Dashboard-

Change a home page content in Sitecore XM Cloud-

In the Zap runs you should be able to see a mail is triggered-

Thats it. This took me few minutes to configure and test the mail for a simple sceanrio.

Zapier gives you full flexibility to configure the triggers without writing any code based on the conditions to tak action when a Webhook event is triggered in Sitecore XM Cloud.

Hope this helps.

Loading

Sitecore Webhook – Authorise event processing app with Auth0 by Okta

In the previous posts we saw how to setup the local environment or XM Cloud to debug Webhook handler event processing app i.e. web api using ngrok in this blog post and also checked how to configure the authorization using Auth0 by OKTA in this blog post using OAuth2ClientCredentialsGrant authorization.

Continuation to this we will now extend the Web Api to authorize the endpoint called from the Sitecore Webhook handler.

We already configured Auth0 to have API and Machine-to-Machine application we will configure this in Web API and setup the authorization.

The authorization in Web API will be done to check of the request cam from the valid domain i.e. dev-your_dev_id.uk.auth0.com and valid audience i.e. https://sc-xmcloud which should be part of the token.

Lets configure Web API .env file. Create a .env file and add the following-

CLIENT_ORIGIN_URL can aslo be your XM Cloud instance.

"CLIENT_ORIGIN_URL": "https://xmcloudcmsdfsdfsd.localhost",
"AUTH0_AUDIENCE": "https://hello-world.example.com",
"AUTH0_DOMAIN": "dev-your_dev_id.uk.auth0.com"

Setup the authentication –

    public static void AddAppAuth(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                var audience =
                    configuration.GetValue<string>("AUTH0_AUDIENCE");

                options.Authority =
                    $"https://{configuration.GetValue<string>("AUTH0_DOMAIN")}/";
                options.Audience = audience;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = true,
                    ValidateIssuerSigningKey = true
                };
            });
    }

Create a builder to add Authentication service-

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAppAuth(builder.Configuration);

Decorate the controller wiht Authorize attribute-

The endpoint for local is – https://localhost:7024/api/Item/handler

Setup ngrok to listen to this endpoint

ngrok http --host-header="localhost:7024" https://localhost:7024

ngrok listening now listening on this URL-

https://8a18b6e7e0c1.ngrok.app

Configure the ngrok endpoint in Sitecore Webhook handler

OAuth2ClientCredentialsGrant authorization looks like this-

Webhook Event

Webhook will fire when the Home item or its descendants are saved

Once saved local instance should Authorize and start executing the action method

We can also see the token and the request successfully processed.

Negative testing-

If the audience and the domain doesn’t match should not execute the action method.

I changed the same in .env file.

CLIENT_ORIGIN_URL=https://xmcloudcmxmcloudcm.localhost
AUTH0_AUDIENCE=https://sc-xmcloud-fake-audience
AUTH0_DOMAIN=dev-fakedomain.uk.auth0.com

Sitecore logs also show the request was failed and this due to incorrect domain and audience configured in Web Api-

3896 16:00:20 ERROR Webhooks: Request is not successfull https://8a18b6e7e0c1.ngrok.app/api/Item/handler. Response code was Unauthorized

ngrok helps debug the event processing app to check the authorization.

Hope this helps.

Loading

Configure Sitecore XM Cloud webhook for Authorization using Auth0 by Okta

In previous blog post we saw how to create a Webhook and debug, inspect and test the Webhook handler using ngrok.

Continuation to the previous blog post lets see how to configure the Webhook to use Client Credential grant and secure the Webhook handler in this blog post with Auth0 by Okta.

Register and Login to Auth0

I used free (development) plan to register to Auth0 if you don’t have the account already. This should create a dev id based on the region you selected and should look like this – dev-your_dev_id

https://auth0.com/pricing

Create a API

Navigate to Applications ==> APIs and Create a new API

Provide the name and identifier-

Once created note down the Identifier-

You will also notice that a new Machine To Machine (M2M) Application is created and is mapped and authorized in this API-

Navigate to Applications ==> Applications to see the M2M application-

Note the Domain, Client ID and Client Secret in this application, as this will be required when configuring the Autjorization is Sitecore.

Generate token using postman

Lets test the API and application ocnfigured correctly by generating token using postman-

You will following from above-

Domain Name- dev-your_dev_id.uk.auth0.com

client_id – cC6kPo4AJvY2spdWqZQVuEOjWTMfUZIo

client_secret- wXmuRusYhjJOF12RljeJ5WiJDL6vXnUKuUJO6961CeKG6xafRJpEuBZh_FAbl617

identifier/audience – https://sc-xmcloud

Post request to generate token – https://dev-your_dev_id.uk.auth0.com/oauth/token

Create a Authorization in XM CLoud-

Craee a new OAuth2ClientCredentialsGrant in Authorization folder. This should be available in following path in Sitecore-

/sitecore/system/Settings/Webhooks/Authorizations

Setup the OAuth2ClientCredentialsGrant

Setup the Authority URL, Client ID, Client Secret, Header Prefix and OptionalParameter as follows- This values we noted above whilst creating a API and Application in Auth0.

Setup Webhook Handler

Create a new Webhook handler and provide the newly created authorization –

For testing purpose I have set the

Event – item_saved, Rule – When the Home Item or its descendants are changed

Url – https://webhook.site/a4624c9e-7dda……

Webhook.site should listen to any calls from Sitecore for testing purpose. This can be your Webhook handler app.

Authorization – Select the newly created authorization to Auth0 which create a token

Serialization Type- JSON

Fire a webhook

Save a home or its descendants to fire a webhook

On save it should fire a webhook which can be seen in webhook.site which should also pass the newly created token.

We can see the token was successfully created and a webhook was fired on saving a Home item as configured in Auntorization and Webhook Handler.

Errors-

If the request to Auth0 fails you should be able to see the same in logs- something like this due to configuration-

4016 12:37:00 INFO  AUDIT (sitecore\sandeep@): Save item: master:/sitecore/content/scxmcloud/sxastarter/Home, language: en, version: 1, id: {0B5C4B64-2A85-4F98-B928-0E0B40C68AEA}
1928 12:37:01 ERROR Webhooks: Token request failed with error: Unauthorized

I have tried this in my local instance but the same can also be done in XM Cloud.

Next we will create a Web Api which should be able to validate the token and executes any custom implementation. This will be in next blog.

Hope this helps.

Loading