Token-Based Authorization with Sitecore Services Client

Santosh Kumar
4 min readJul 24, 2024

--

Token-based authorization is a modern approach to authentication that allows users to securely access resources. In the context of Sitecore Services Client, token-based authorization enhances security by ensuring that each request is authenticated. This article will guide you through implementing token-based authorization with Sitecore Services Client.

What is Token-Based Authorization?

Token-based authorization involves the use of tokens, which are temporary credentials issued to clients after authentication. These tokens are included in the headers of requests to verify the identity of the requester.

Benefits of Token-Based Authorization

  • Security: Reduces the risk of session hijacking.
  • Scalability: Tokens are stateless, making it easier to scale applications.
  • Decoupling: Simplifies the architecture by decoupling the authentication server from the resource server.

Step-by-Step Implementation

1. Configuring Sitecore for Token-Based Authentication

First go to the Sitecore.Services.Client.config file in /App_Config/Sitecore/Services.Client folder.

Enable the token authorization by changing this setting to true and make sure the AllowAnonymousUser setting is set to false.

<setting name="Sitecore.Services.Token.Authorization.Enabled" value="true" />
<setting name="Sitecore.Services.AllowItemServiceAnonymousUser" value="false" />

2. Configuring the Signing Provider

Add a patch file in “/App_Config/Include” folder to configure the Signing Provider.

<?xml version="1.0" encoding="utf-8"?>

<configuration>
<sitecore>
<api>
<tokenSecurity>
<signingProvider type="Sitecore.Services.Infrastructure.Security.SymmetricKeySigningProvider, Sitecore.Services.Infrastructure">
<param desc="connectionstringname">Sitecore.Services.Token.SecurityKey</param>
</signingProvider>
</tokenSecurity>
</api>
</sitecore>
</configuration>

3. Add a new connection string

Convert your key to Base64 format, replace ‘xxxxx’ with your encoded key, and add it to your ConnectionStrings.config file located in the App_Config folder.

 <add name="Sitecore.Services.Token.SecurityKey" connectionString="key=xxxxx" />

4. Test with Postman

Once all the recommended changes have been implemented, the token-based authentication mechanism will be enabled and ready for testing.

To begin, attempt to access an item without providing a token; the expected response should be like this.

Next, generate a token for a user who has access to the item you want to retrieve. For simplicity and testing purpose, you can generate a token for the Sitecore admin login.

Now, revisit your previous request and add the generated token to the request header. This time, you should receive a 200 OK response.

You can also validate this token in JSON Web Tokens — jwt.io

Token Generation Endpoint — API

You can also create a controller action to generate tokens. Here are the steps:

Step 1 — Create a TokenManager class that will handle token generation and validation.

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

namespace YourNamespace.Security
{
public static class TokenManager
{
private static readonly string SecretKey = "Your-Secret-Key"; // Replace with your secret key
private static readonly string Issuer = "YourIssuer";
private static readonly string Audience = "YourAudience";

public static string GenerateToken(string username)
{
var securityKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(SecretKey));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(Issuer,
Audience,
new[]
{
new Claim(ClaimTypes.Name, username)
},
expires: DateTime.Now.AddMinutes(30),
signingCredentials: credentials);

return new JwtSecurityTokenHandler().WriteToken(token);
}

public static bool ValidateToken(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Issuer,
ValidAudience = Audience,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(SecretKey))
};

try
{
tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
return true;
}
catch
{
return false;
}
}
}
}

Step 2 — Create a Token Generation Endpoint: Implement an endpoint in your Sitecore solution that generates tokens upon successful authentication.

using System.Web.Http;

public class AuthenticationController : ApiController
{
[HttpPost]
public IHttpActionResult GenerateToken(LoginModel login)
{
if (IsValidUser(login))
{
var token = TokenManager.GenerateToken(login.Username);
return Ok(new { token });
}
return Unauthorized();
}

private bool IsValidUser(LoginModel login)
{
// Implement your user validation logic here
return login.Username == "admin" && login.Password == "password"; // Example validation
}
}

Step 3 — Protecting API Endpoints

In your controllers, add token validation logic.

using System.Web.Http;

public class SecureDataController : ApiController
{
[HttpGet]
[Authorize]
public IHttpActionResult GetSecureData()
{
var token = Request.Headers.Authorization.Parameter;
if (TokenManager.ValidateToken(token))
{
return Ok("Secure Data");
}
return Unauthorized();
}
}

That’s it. Implementing token-based authorization in Sitecore Services Client enhances the security and scalability of your application. By following the steps outlined in this article, you can securely protect your Sitecore API endpoints and ensure a robust authentication mechanism.

You can find my other blogs here.

Thank you!

--

--

Santosh Kumar

Software Architect at EPAM Systems. Extensive expertise in Sitecore | XM Cloud | OrderCloud | Content Hub |.Net Core | Azure | AWS | Docker & MACH architecture.