Securing and Authorizing Custom API Operations

TABLE OF CONTENTS


Overview

  • Audience: Partner developers and client technical teams who build or review custom endpoints with the Znode Custom API SDK.
  • Product: Znode 10.x. Code examples were checked against Custom API SDK 10.13.1.0.
  • Components: Znode API gateway; Custom API SDK projects Engine.Custom.Api, Custom.Api.Core, Custom.Admin.Core and Custom.Libraries.Event; Admin Console Dev Center (Roles & Access Rights, Webhook Settings, Method Override).
  • Prerequisites: A working custom endpoint (see the series guide Creating a Custom Znode API Endpoint); a way to obtain tokens for your environment (see Authenticating to Znode APIs); the gateway URL and API client credentials for a development environment.

This guide shows how to make every operation you add to the Znode Custom API follow the Znode authentication and authorization model. After reading it you can route a custom endpoint so the Znode API gateway authenticates every call, take the caller's identity only from trusted sources, check roles, custom permissions, record ownership and store scope in your own code, and protect the endpoints that Znode itself calls (webhooks, method overrides and Admin custom pages).

  • The Znode API gateway answers who is calling. It authenticates the token or client credentials and routes the call to your Custom API.
  • Your custom code answers may this caller do this, to this record, in this store. Nothing in Znode does that for a custom operation.
  • Take the user, role and store from a credential your endpoint verifies or from your own server, never from an id in the URL or body or an identity header the client could have sent.

A custom API operation runs with the same reach as Znode's own APIs: it can read orders, carts, accounts and custom tables through the Znode API clients. If the operation trusts the wrong input, one shopper can read another shopper's order, or a guest can trigger a back-office action. This guide explains where Znode protects you and where your code must take over.

The Znode API Customization Guide states the ground rule: custom APIs operate within the existing Znode authentication model, and custom API calls are routed through the API gateway. In practice that splits the work into two layers.

LayerWho does itWhat it decides
AuthenticationZnode API gatewayIs the token or client credential valid? Unauthenticated calls stop here with 401.
IdentityYour endpoint: from a Basic call it verified as your own server's, or from gateway headers on user-token calls once confirmed (section 3.2)Which user, role and store the call is for.
AuthorizationYour custom codeWhether this caller may run this operation on this record in this store.

When this guide applies

  • Any new controller action in Custom.Api.Core that a Webstore, headless app, mobile app or integration calls through the gateway.
  • A custom route that wraps a Znode operation (your code runs before Znode's, so it must apply at least the same rules). Taking over a standard Znode route path is unconfirmed; see the note in section 6.1.
  • Endpoints that Znode calls: webhook receivers, Method Override receivers and Admin custom pages served from Custom.Admin.Core.

What this guide does not cover

  • How to obtain, refresh and revoke tokens in detail.
  • How to scaffold a controller, service and route.
  • Admin Console menu access for built-in screens. That is configured in Dev Center > Roles & Access Rights and needs no code.

Glossary

TermMeaning in this guide
API gatewayThe single entry point for Znode APIs. It authenticates each call and routes it by path to the service that owns it. Your Custom API sits behind it.
Basic authenticationAuthorization: Basic <base64>, where the encoded value is <client-name>|<client-key>: the client name and client key for your environment, joined with a pipe. In the Custom API settings these are stored as ZnodeApiDomainName and ZnodeApiDomainKey. The pipe is what the Custom API SDK sends and validates and works on every release; a colon separator is accepted only from Znode 10.10.0.0. For server-to-server calls only. Never place the key in browser or mobile code. See Authenticating to Znode APIs for details.
JWT Bearer tokenAuthorization: Bearer <token>. An application token comes from POST /Token; a user token comes from POST /UserToken and carries the user's claims.
Identity headersRequest headers that say who the call is for, such as Znode-UserId, Znode-PortalCode and the Znode-JWT-* headers the gateway derives from a user token on Znode routes. Never base an authorization decision on one a client could have sent (section 3.2).
RoleA named bundle of access (Admin, Commerce Portal, B2B or Customer role types) managed in Dev Center > Roles & Access Rights.
Custom permissionA permission you define (Object, Permission Name, Permission Code, Application Type) and allow per role. Znode stores and returns it but does not enforce it. Your code enforces it.
Ownership checkProof that a record id supplied by the caller (user, account, order, cart, address, quote) belongs to the caller, their account or their store.
Store scopeThe store (portal) a call is limited to, sent in the Znode-PortalCode header. With a missing or wrong store code, operations that validate it return 400 "Please check the PortalCode."; other operations return an empty result.
Route key customapiThe Key value that tells the gateway to send a route from CustomOcelot.json to your Custom API.

Custom API Flow

Request flow: callers (Webstore or your BFF, signed-in user session, server integration) reach the Znode API gateway, which 1 authenticates, 2 adds identity headers and 3 routes the request; your custom endpoint then 4 verifies caller identity, 5 checks the action, 6 checks the data and 7 validates input; 8 typed clients call the Znode Core v2 and Commerce APIs. Separately, the Znode platform (webhook, Method Override, Admin custom page) calls your receiver endpoint with the Authorization header you configured.

Authentication happens at the Znode API gateway; authorization happens in your custom endpoint. Znode-initiated calls carry the Authorization value you configured.

  1. Your application. A server sends Basic client credentials or an application token. A signed-in user session sends a user token. Every route except the token routes, health and Swagger pages needs authentication. Expected result: an unauthenticated call receives 401 from the gateway and never reaches your code.
  2. API Gateway - Adds Identity. For a user token, the gateway is documented to set the user, store and role headers (Znode-JWT-*) from the token's claims for downstream Znode routes. Whether it forwards them on customapi routes, and whether it overwrites a value the client sent, is unconfirmed. With Basic, the calling server sends Znode-UserId itself where an operation needs a user (0 for a guest).
  3. API Gateway -  routes the call. A route in Engine.Custom.Api/Ocelot/CustomOcelot.json with "Key": "customapi" sends the request to your Custom API. The SDK's Ocelot folder also contains a sample catch-all route for /CustomPortal/{everything} (in Custom.json). Every route that reaches your code through the gateway needs the checks below.
  4. Custom API - establishes the caller identity as described in section 3.2: from a credential it verifies or a server-side lookup, never from an id in the route, query string or body, and never from an identity header the client could have sent.
  5. Custom API - checks the action: the caller's role, or a custom permission you defined for that role.
  6. Custom API - checks the data: the record belongs to the caller, their account or their store.
  7. Custom API - validates the input: types, ranges, lengths and allowed values.
  8. Custom API - calls Znode APIs  through the typed API clients with its own configured credentials, passing the caller's own user id and store, so Znode's own checks apply to the right user.

Note: The Custom API SDK template does not add authorization checks for you. Its sample controllers carry no [Authorize] attribute, and two samples (CustomPortalController.GetOrderList and CustomCPController.GetCartItemList) accept a user id from the URL. Treat those samples as plumbing examples only. 

Who calls a custom endpoint

CallerHow it authenticatesWhere the user identity comes fromTrust level
Webstore or your BFF (server side)Basic client credentials or an application tokenZnode-UserId set by your server from its own sessionOnly after your endpoint verifies the Basic header is your own server's
Signed-in user session through your BFFBearer user token from POST /UserTokenZnode-JWT-* headers the gateway derives from the token (unconfirmed on custom routes)Logging only until the check passes; then still check role and ownership
Server integration or scheduled jobBasic or an application tokenNone, or a service user your integration ownsTrusted for the actions you allow that client
Znode webhook or Method OverrideThe Authorization value typed in the Admin Console, sent exactly as typedThe event payloadOnly after your receiver validates the secret
Admin custom page (content type URL)Basic header built from the Admin Console's client name and client keyNone (the Admin Console server fetches the page)Only after the header is validated

Browser code must never hold client credentials. A headless or mobile front end puts a thin server (a BFF) in front of Znode, as the Webstore does. That rule is what makes a Basic call trustworthy: only your servers can make one, provided your endpoint verifies the Basic header itself.

Identifying the caller

For a user token, the gateway is documented to set the Znode-JWT-* identity headers for downstream Znode routes. Whether it forwards them on customapi routes, and whether it overwrites a Znode-JWT-* or Znode-UserId value that the client sent itself, is unconfirmed. Any caller with a valid token can add these headers to its own request, so your endpoint must establish the caller itself:

  1. Never base an authorization decision on a client-sent Znode-UserId or Znode-JWT-* header. Until you have confirmed otherwise, use their values for logging and correlation only.
  2. Establish identity in your endpoint. For a call from your own server (the Webstore or your BFF), require the Basic header and verify in your endpoint that it carries your server's client name and client key (section 6.5); only then use the Znode-UserId that your server set from its own signed-in session. Alternatively, look the user up server-side from a session or record your own server holds, never from an id the caller supplies.
  3. Use the gateway's Znode-JWT-* headers on a user-token call only after the check below passes in that environment, and record the result in configuration. Repeat the check after every Znode upgrade.
  4. If no verified identity is available, treat the caller as a guest (user id 0) and refuse user-specific operations.
HeaderSet byHow a custom endpoint may use it
Znode-JWT-UserIdGateway, from a user token (documented for Znode routes)Logging only until the check below passes; then the signed-in user's id
Znode-JWT-UserRoleNameGateway, from a user token (documented for Znode routes)Logging only until the check below passes; then the user's role names (comma separated)
Znode-JWT-PortalCodeGateway, from a user token (documented for Znode routes)Logging only until the check below passes; then the store the user signed in to
Znode-UserIdThe calling server on a Basic call; the gateway from a user token on Znode routesOnly on a call whose Basic header your endpoint verified as your own server's
Znode-PortalCode / Znode-StoreCodeThe calling serverStore context for Znode calls. Required for store-specific data

Important

Never send, and never accept, a user id from the browser. On a user-token call the user is the token's user, read only after the check above passes; on a server call it is the user your own server's session holds, accepted only after your endpoint verifies the Basic header.

Decide the Access Model for Each Operation

Before writing code, write one line per operation that says who may call it and which records it may touch. Use the table to pick the checks.

Operation typeExampleRequired checks
Public readStore locator, published content from a custom tableGateway authentication; store scope; rate limits and caching. No user identity needed
Shopper's own dataMy saved lists, my warranty registrationsVerified user identity (section 3.2); ownership of every id; store scope
B2B account dataAccount-level price agreements, account documentsUser identity; account membership and account role; store scope
Back-office actionExport orders, re-send to ERPRole check or custom permission; audit log; never callable from a shopper session
Server-to-server onlyERP pushes stock, nightly syncClient credentials of that integration only; validate the Basic header or restrict the route to that client
Znode calls youWebhook, Method Override, Admin custom pageValidate the Authorization value in constant time; HTTPS; idempotent handling

Check it in your custom code when…

  • The rule is specific to your operation or your data.
  • The record lives in a custom table or an external system.
  • You defined a custom permission for it.

Rely on Znode when…

  • You call a Znode API with the caller's own user id and store, and that API already validates the user.
  • The gateway must reject a missing or invalid token (it always does).
  • Admin menu access for built-in screens (Roles & Access Rights).

Step-by-Step: Secure a Custom Operation

Every custom operation runs the same chain of checks after the gateway has authenticated the call. The diagram shows the order and the response for each failure.

Checks inside every custom operation, in order: 1 Identity (fails with 401 Unauthorized, no user identity), 2 Action (403 Forbidden, role not allowed), 3 Ownership (404 Not Found, not the caller's), 4 Store scope (403 Forbidden, store mismatch), 5 Validate and run (400 Bad Request, invalid input).

The checks inside a custom operation, in order, with the response to return when a check fails.

  1. Write the access rule. For the operation, record the caller type, the required role or custom permission, and the records it may touch. Expected result: one line per operation that a reviewer can check.
  2. Route it through the gateway. Add an entry to Engine.Custom.Api/Ocelot/CustomOcelot.json with "Key": "customapi". Expected result: a call to <your-gateway-url>/<your-route> without a token returns 401.
  3. Give callers only the gateway URL. Host the Custom API in the same network as the Znode API, as Znode recommends, and do not publish the Custom API host's own address to storefronts or integrations. Where you control the network, block direct public access to that host. Expected result: every documented call to your operation goes through <your-gateway-url>.
  4. Establish the caller identity. Run the gateway check, add the CallerContext helper and use it in every action that needs a user. Expected result: no action takes a user id, account id or store code from the route, query string or body, and no action authorizes on an identity header the client could have sent.
  5. Check the action. Add a role check or a custom permission check. Expected result: a caller without the role receives 403.
  6. Check ownership and store. Verify every record id the caller supplies. Expected result: user A asking for user B's record receives 404.
  7. Validate input. Use request models with bounds; cap page sizes; never concatenate input into SQL (see Implementing Validation in Custom APIs). Expected result: out-of-range input returns 400.
  8. Protect Znode-initiated endpoints. Validate the Authorization value on webhook and Method Override receivers, and the Basic header on Admin pages. Expected result: a call with a missing or wrong secret returns 401.
  9. Restrict CORS. Replace the template's allow-any-origin policy. Expected result: a browser on an unlisted origin is blocked.
  10. Run the test matrix in section 8 on a development environment. Expected result: every row returns the expected status.

Code Examples

All examples target the Custom API SDK (.NET 8, implicit usings and nullable reference types enabled, as in Custom.Api.Core.csproj). Replace every value in angle brackets. Keep secrets in environment variables or a vault, never in appsettings.json.

Route the operation through the gateway

Add one entry per operation to Engine.Custom.Api/Ocelot/CustomOcelot.json. The shape matches the entries the SDK ships. List only the HTTP methods the operation uses.

JSON, CustomOcelot.json (Routes entry):

{
 "DownstreamPathTemplate": "/CustomOrders/MyOrders",
 "UpstreamPathTemplate": "/CustomOrders/MyOrders",
 "UpstreamHttpMethod": [ "GET" ],
 "Key": "customapi",
 "SwaggerKey": "customapi",
 "Priority": 1
}

Establish the caller identity

This helper never authorizes on an identity header by default. It always records the claimed user id for logging and correlation, and fills UserId and Roles only after a check you control: either the action has verified that the call carries your own server's Basic credential (then it uses Znode-UserId), or the environment's configuration records that the gateway check passed (then it uses the Znode-JWT-* headers). Otherwise the caller is a guest. Add it to Custom.Api.Core.

C#, Custom.Api.Core/Helper/CallerContext.cs:

using Microsoft.AspNetCore.Http;
namespace Custom.Api.Core
{
 /// <summary>Caller identity. Identity headers count only after a check you confirmed.</summary>
 public sealed class CallerContext
 {
 public const string JwtUserIdHeader = "Znode-JWT-UserId";
 public const string JwtRoleHeader = "Znode-JWT-UserRoleName";
 public const string JwtPortalHeader = "Znode-JWT-PortalCode";
 public const string UserIdHeader = "Znode-UserId";
 public const string PortalHeader = "Znode-PortalCode";
 /// <summary>Set to true per environment only after the section 3.2 gateway check passes.</summary>
 public const string GatewayHeadersConfirmedKey = "<your-section>:GatewayIdentityHeadersConfirmed";
 public int UserId { get; private init; }
 public IReadOnlyList<string> Roles { get; private init; } = Array.Empty<string>();
 public string? TokenPortalCode { get; private init; }
 public string? PortalCode { get; private init; }
 /// <summary>Raw user id header value, for logging and correlation only. Never authorize on it.</summary>
 public string? ClaimedUserId { get; private init; }
 public bool IsSignedIn => UserId > 0;
 /// <param name="request">The incoming request.</param>
 /// <param name="gatewayHeadersConfirmed">True only when configuration records that the gateway check passed here.</param>
 /// <param name="serverCredentialVerified">True only when this action verified the Basic header as your own server's.</param>
 public static CallerContext FromRequest(HttpRequest request, bool gatewayHeadersConfirmed, bool serverCredentialVerified)
 {
 IHeaderDictionary headers = request.Headers;
 string jwtUserId = headers[JwtUserIdHeader].ToString();
 string serverUserId = headers[UserIdHeader].ToString();
 int userId = 0;
 string roles = string.Empty;
 string tokenPortal = string.Empty;
 if (gatewayHeadersConfirmed && jwtUserId.Length > 0)
 {
 // Confirmed: the gateway sets this from a user token and overwrites client values.
 if (!int.TryParse(jwtUserId, out userId) || userId < 0)
 userId = 0;
 roles = headers[JwtRoleHeader].ToString();
 tokenPortal = headers[JwtPortalHeader].ToString();
 }
 else if (serverCredentialVerified &&
 int.TryParse(serverUserId, out int verifiedUserId) && verifiedUserId > 0)
 {
 // Sent by your own server, whose Basic credential this action verified.
 userId = verifiedUserId;
 }
 string portal = headers[PortalHeader].ToString();
 string claimed = jwtUserId.Length > 0 ? jwtUserId : serverUserId;
 return new CallerContext
 {
 UserId = userId,
 Roles = roles.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
 TokenPortalCode = string.IsNullOrEmpty(tokenPortal) ? null : tokenPortal,
 PortalCode = string.IsNullOrEmpty(portal) ? null : portal,
 ClaimedUserId = string.IsNullOrEmpty(claimed) ? null : claimed
 };
 }
 /// <summary>Reads the confirmation flag; anything other than "true" means not confirmed.</summary>
 public static bool GatewayHeadersConfirmed(Microsoft.Extensions.Configuration.IConfiguration configuration) =>
 bool.TryParse(configuration[GatewayHeadersConfirmedKey], out bool confirmed) && confirmed;
 public bool IsInRole(string roleName) =>
 Roles.Any(r => string.Equals(r, roleName, StringComparison.OrdinalIgnoreCase));
 /// <summary>The store for this call. A token's store wins; a different header store is a mismatch.</summary>
 public bool TryGetStore(out string? storeCode)
 {
 if (TokenPortalCode is not null && PortalCode is not null &&
 !string.Equals(TokenPortalCode, PortalCode, StringComparison.OrdinalIgnoreCase))
 {
 storeCode = null;
 return false;
 }
 storeCode = TokenPortalCode ?? PortalCode;
 return storeCode is not null;
 }
 }
}

What to change: replace <your-section> with your own configuration section. Leave GatewayIdentityHeadersConfirmed unset (false) until the check passes in that environment, and set it per environment, never in the shared appsettings.json. Pass serverCredentialVerified: true only from an action that has verified the Basic header. ClaimedUserId may go into your logs for correlation; never use it in a check.

Check ownership: replace ids from the URL

The SDK sample CustomPortalController.GetOrderList is routed as GetOrderList/{userId}/{portalCode}. Any authenticated caller can change userId in the URL and read someone else's orders. The safe version takes no user id from the caller. It reuses the sample service ICustomService.GetOrderList(string userId, string portalCode), which already sends Znode-UserId and Znode-PortalCode to the Commerce API through SetCustomHeadersExplicitly.

C#, Custom.Api.Core/Controllers/CustomPortalController.cs (do not copy):

// Unsafe (SDK sample shape): identity comes from the URL.
[HttpGet]
[Route("GetOrderList/{userId}/{portalCode}")]
public IActionResult GetOrderList(string userId, string portalCode) { ... }

C#, Custom.Api.Core/Controllers/CustomOrdersController.cs:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Znode.Engine.CommercePortal.Client;
namespace Custom.Api.Core
{
 [Route("[controller]")]
 [ApiController]
 public class CustomOrdersController : ControllerBase
 {
 private readonly ICustomService _customService;
 private readonly IConfiguration _configuration;
 public CustomOrdersController(ICustomService customService, IConfiguration configuration)
 {
 _customService = customService;
 _configuration = configuration;
 }
 /// <summary>Returns the signed-in caller's own orders in the caller's store.</summary>
 [HttpGet("MyOrders")]
 public IActionResult MyOrders()
 {
 CallerContext caller = CallerContext.FromRequest(Request,
 CallerContext.GatewayHeadersConfirmed(_configuration), serverCredentialVerified: false);
 if (!caller.IsSignedIn)
 return Unauthorized(); // 1 identity
 if (!caller.TryGetStore(out string? storeCode))
 return StatusCode(StatusCodes.Status403Forbidden); // 4 store scope
 CollectionResponseModel orders =
 _customService.GetOrderList(caller.UserId.ToString(), storeCode!);
 return Ok(orders);
 }
 }
}

Until the check passes and the flag is set, MyOrders answers 401 to every call: deny by default. If your own server calls the operation instead, protect the action with your copy of the Basic header check and pass serverCredentialVerified: true.

For an operation that takes a record id (an order number, a cart number, a row in a custom table), load the record with the caller's own user id, or load it and compare its owner with caller.UserId before returning anything. Return 404 when it is not the caller's, so the response does not confirm that the id exists.

Check the action: role or custom permission

For a role check, use the role names the gateway derived from a user token. CallerContext fills them only when the check has passed in that environment; until then the check below denies every call.

C#, role check in a controller action:

// _configuration: IConfiguration injected in the controller constructor, as in section 6.3.
CallerContext caller = CallerContext.FromRequest(Request,
 CallerContext.GatewayHeadersConfirmed(_configuration), serverCredentialVerified: false);
if (!caller.IsSignedIn) return Unauthorized();
if (!caller.IsInRole("<your-role-name>")) return StatusCode(StatusCodes.Status403Forbidden);

For finer control, define a custom permission in Dev Center > Roles & Access Rights, open a role, tab Custom Permissions, then Add Permission. Pick the Application Type (Admin, Commerce Portal, Webstore or Others), enter Object, Permission Name and Permission Code (lower case, up to 50 characters), select it for the roles that may use it, and save the role. Znode stores the permission and returns it, but no Znode screen or API enforces it: your endpoint must.

Your endpoint reads the permissions for a user with GET /v2/custom-permissions/roles/{usernames}. The response holds PermissionsByRole[], each with RoleName and CustomPermissionsList[] of Object, PermissionCode, PermissionName, ApplicationType and IsAllowed. The checker below denies by default when the call fails.

C#, Custom.Api.Core/Services/CustomPermissionChecker.cs:

using System.Net;
using System.Text.Json;
namespace Custom.Api.Core
{
 public interface ICustomPermissionChecker
 {
 Task<bool> IsAllowedAsync(string userName, string permissionCode, CancellationToken ct);
 }
 public sealed class CustomPermissionChecker : ICustomPermissionChecker
 {
 private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true };
 private readonly IHttpClientFactory _httpClientFactory;
 public CustomPermissionChecker(IHttpClientFactory httpClientFactory)
 {
 _httpClientFactory = httpClientFactory;
 }
 public async Task<bool> IsAllowedAsync(string userName, string permissionCode, CancellationToken ct)
 {
 try
 {
 HttpClient client = _httpClientFactory.CreateClient("znode-gateway");
 using HttpResponseMessage response = await client.GetAsync(
 $"v2/custom-permissions/roles/{Uri.EscapeDataString(userName)}", ct);
 if (response.StatusCode != HttpStatusCode.OK)
 return false; // deny by default
 await using Stream body = await response.Content.ReadAsStreamAsync(ct);
 PermissionsByUser? data =
 await JsonSerializer.DeserializeAsync<PermissionsByUser>(body, JsonOptions, ct);
 return data?.PermissionsByRole?.Any(role =>
 role.CustomPermissionsList?.Any(p =>
 p.IsAllowed && string.Equals(p.PermissionCode, permissionCode, StringComparison.Ordinal)) == true) == true;
 }
 catch (Exception)
 {
 return false; // deny by default
 }
 }
 private sealed class PermissionsByUser { public List<RolePermissions>? PermissionsByRole { get; set; } }
 private sealed class RolePermissions
 {
 public string? RoleName { get; set; }
 public List<Permission>? CustomPermissionsList { get; set; }
 }
 private sealed class Permission
 {
 public string? PermissionCode { get; set; }
 public bool IsAllowed { get; set; }
 }
 }
}

Register the checker and a named client in CustomDependencyRegistration.RegisterCustomDI. The client reads the gateway URL and the API client credentials from configuration; supply the values through environment variables. The Basic value joins the client name and client key (ZnodeApiDomainName and ZnodeApiDomainKey) with a pipe (|), the same format the Webstore sends and ValidateAuthHeader reads. Use the pipe: a colon separator is accepted only from Znode 10.10.0.0, while the pipe works on every release.

C#, Custom.Api.Core/App_Start/CustomDependencyRegistration.cs:

// Requires: using Microsoft.Extensions.Configuration;
builder.Services.AddScoped<ICustomPermissionChecker, CustomPermissionChecker>();
builder.Services.AddHttpClient("znode-gateway", (sp, client) =>
{
 IConfiguration config = sp.GetRequiredService<IConfiguration>();
 string gateway = config["AppSettings:ZnodeApiGateway"]!.TrimEnd('/') + "/";
 string credentials = $"{config["AppSettings:ZnodeApiDomainName"]}|{config["AppSettings:ZnodeApiDomainKey"]}";
 client.BaseAddress = new Uri(gateway);
 client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
 "Basic", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(credentials)));
});

Note: Cache permission results briefly (for example, a few minutes per username) so a permission check does not add a Znode call to every request. Clear or shorten the cache when roles change often.

Server-to-server and Admin custom pages: validate the Basic header

The SDK includes ValidateAuthHeaderAttribute in Custom.Admin.Core/Attribute. It decodes Authorization: Basic <base64>, splits the value on | into client name and client key, and compares them with AppSettings:ZnodeApiDomainName and AppSettings:ZnodeApiDomainKey. On a mismatch it returns 401 with the message "You are unauthorized to access this resource." The sample StoreController applies it to the whole controller:

C#, Custom.Admin.Core/Controllers/StoreController.cs (SDK sample):

using Custom.Admin.Core.Attribute;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
namespace Custom.Admin.Core
{
 [ValidateAuthHeader]
 public class StoreController : Controller
 {
 [EnableCors("ZnodeAdminURLCorsPolicy")]
 [HttpGet]
 public virtual ActionResult StoreDetails(string StoreCode, string PortalID) { ... }
 }
}
  • Apply [ValidateAuthHeader] to every Admin custom page controller. The Admin Console server fetches a URL-type custom page with a Basic header built from its client name and client key.
  • Custom.Api.Core does not reference Custom.Admin.Core. To use the same check on a server-to-server endpoint in Custom.Api.Core, copy the attribute into that project or add a project reference.
  • When you copy it, compare the decoded values with CryptographicOperations.FixedTimeEquals instead of String.Compare, and reject a header that does not start with Basic .
  • Unconfirmed: whether the gateway forwards the caller's Authorization header to your Custom API on a customapi route. The test endpoint in section 3.2 logs header names; confirm that Authorization reaches it on a Basic call before relying on this check for gateway-routed calls.

Webhooks and Method Overrides: validate the secret

Znode sends the Authorization value you enter in Dev Center > Webhook Settings or Dev Center > Method Override exactly as typed, in the Authorization header. Nothing else signs the request. The SDK's OverrideEventSubscriberController (route ~/callback-event-subscriber) does not check that header, so add the check:

C#, Custom.Libraries.Event/Controllers/OverrideEventSubscriberController.cs:

using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Configuration;
[HttpPost]
[EnableCors("ZnodeAdminURLCorsPolicy")]
[Route("~/callback-event-subscriber")]
public async Task<IActionResult> SubscribeOverrideEvent([FromBody] OverrideZnodeActionEvent eventNotification)
{
 string? expected = _configuration["<your-section>:MethodOverrideSecret"]; // from a vault or environment variable
 string received = Request.Headers["Authorization"].ToString();
 if (string.IsNullOrEmpty(expected) ||
 !CryptographicOperations.FixedTimeEquals(
 Encoding.UTF8.GetBytes(received), Encoding.UTF8.GetBytes(expected)))
 {
 return Unauthorized();
 }
 if (eventNotification == null || string.IsNullOrEmpty(eventNotification.EventType) ||
 string.IsNullOrEmpty(eventNotification.EventPayload))
 {
 return BadRequest("The event data provided is invalid. Please verify the request and try again.");
 }
 var status = await _subscriberService.SubscribeOverrideEvent(eventNotification);
 return status != null ? Ok(status) : UnprocessableEntity();
}

What to change: inject IConfiguration as _configuration in the controller constructor, choose your own configuration key, and enter the identical value (for example Bearer <your-secret>) in the Admin Console Authorization field. Use the same pattern for webhook receivers.

  • A Method Override that receives 401 fails safe: Znode continues with its default result.
  • Webhooks are fire and forget with a 5-second timeout and no retry. Answer 200 quickly and queue your own work.
  • Never put the secret in the webhook URL, and never log the Authorization header or the SecretKey field.

Restrict CORS to your storefront origins

The template's Program.cs registers a default CORS policy with AllowAnyOrigin(). The SDK already contains RegisterCorsPolicy() in Engine.Custom.Api/RegistrationHelper.cs, which reads a comma-separated list from AppSettings:ZnodeCorsAllowedURLS. Replace the AddCors block in Program.cs with:

C#, Engine.Custom.Api/Program.cs:

// Register a default CORS policy limited to AppSettings:ZnodeCorsAllowedURLS.
builder.RegisterCorsPolicy();

Expected result: browsers on origins outside ZnodeCorsAllowedURLS are blocked. If the setting is empty, no default policy is registered and cross-origin browser calls are refused. Admin pages and override callbacks use the separate named policy ZnodeAdminURLCorsPolicy, built from AppSettings:ZnodeAdminURLCorsPolicy.

Calling the secured operation

Obtain a user token, then call the custom route through the gateway. The token routes take a JSON body and need no Authorization header. Run these from your server, never from browser code.

HTTP, request a user token:

POST <your-gateway-url>/UserToken
Content-Type: application/json
{
 "ClientName": "<client-name>",
 "ClientKey": "<client-key>",
 "StoreCode": "<store-code>",
 "UserName": "<user-name>",
 "UserPassword": "<user-password>"
}

HTTP, call the custom operation:

GET <your-gateway-url>/CustomOrders/MyOrders
Authorization: Bearer <access-token>
Znode-PortalCode: <store-code>

Expected result: 200 with the caller's own orders. The token response contains Token, RefreshToken and HasError. Access tokens last 30 minutes and refresh tokens 30 days by default; refresh with POST /RefreshJWTToken and the body {"RefreshToken": "<refresh-token>"}.

Configuration

Custom API host settings live in the appsettings section of Engine.Custom.Api/appsettings.json and can be overridden by environment variables (the host calls AddEnvironmentVariables()). Store secret values only in environment variables or a vault.

SettingPurposeExampleDefault in template
ZnodeApiGatewayBase URL of the Znode API gateway that the Custom API calls<your-gateway-url>Placeholder
ZnodeApiDomainName / ZnodeApiDomainKeyClient name and client key the Custom API uses to call Znode (sent as Basic base64(<client-name>|<client-key>)); also the values ValidateAuthHeader compares inbound Basic headers withSet by environment variablePlaceholder; never commit real values
IsGlobalAPIAuthorizationAuthorization mode switch for outbound Znode client calls (see the note below this table)truetrue
EnableBasicAuthorizationAuthorization mode switch for outbound client calls (see the note below this table)truetrue
ZnodeCorsAllowedURLSComma-separated storefront origins for the default CORS policy (used by RegisterCorsPolicy())https://<your-store-domain>Local development origin
ZnodeAdminURLCorsPolicyComma-separated Admin origins allowed for Admin pages and override callbackshttps://<your-admin-domain>Local development origin
UseDynamicSwaggerJsonWhen true, serves Swagger generated at run time outside Development; when false, a pre-generated file is servedfalsefalse
Admin Console settingWherePurpose
Custom permissionsDev Center > Roles & Access Rights > (role) > Custom PermissionsDefine Object, Permission Name, Permission Code and Application Type; allow per role
Admin store accessAdmin user > Stores fieldLimit an admin user to chosen stores
Webhook AuthorizationDev Center > Webhook Settings > Add Webhook EventValue sent exactly as typed in the Authorization header
Method Override AuthorizationDev Center > Method OverrideValue sent exactly as typed; with none configured a placeholder Basic value is sent
Token lifetimesPlatform settings (JWTExpirySpan, JWTRefreshExpirySpan)Access token 30 minutes, refresh token 30 days by default

Test the Access Model

Run this matrix on a development environment for every new operation. Use two test shoppers (A and B) in the same store, and one user in a second store. Rows 3 to 6 assume the check has passed and GatewayIdentityHeadersConfirmed is set; until then they return 401.

#RequestExpected result
1No Authorization header, through the gateway401 from the gateway: "You are unauthorized to access this resource. Please check your token credentials."
2Expired or revoked tokenRejected by the gateway with 401 (the error code in the body can be 498 for an invalid token)
3Shopper A's user token, A's own record200 with A's data only
4Shopper A's user token, B's record id404 (not 200, not B's data)
5User token for store 2, Znode-PortalCode of store 1403
6User token without the required role or custom permission403
7Request directly to the Custom API host, bypassing the gatewayWhere you control the network: no answer from outside it. Otherwise see the note below this table
8Webhook or override call with a missing or wrong Authorization value401; for overrides, the storefront still completes with default values
9Out-of-range page size or invalid field value400
10Browser call from an origin not in ZnodeCorsAllowedURLSBlocked by the browser (no CORS headers)
11Shopper A's user token plus a forged Znode-JWT-UserId or Znode-UserId header with B's idA's data or 401, never B's data

Note: Check from inside the private network, call <custom-api-host>/CustomSampleEntity/ZnodeDomainList with no Authorization header. If it answers 200 or 204, the gateway and your network are the only protection for direct calls, so keep the host address private and apply the checks in this guide in every action.

Golden Rules

  • Never trust an identity or store value the client can set: user id, account id, role or store code in the route, query string, body or a header, including Znode-UserId and Znode-JWT-*. Take identity from a credential your endpoint verifies or from your own server's session, and use gateway identity headers only after the check passes.
  • Deny by default. If an identity, role, permission or ownership check cannot complete (for example a Znode call fails), return an error. Never fall back to returning the data.
  • Keep client credentials on the server, one API client per integration so one can be revoked alone, and rotate keys periodically.
  • Log ids and counts, never tokens, Authorization headers, card data or personal data. The SDK's IZnodeLogging is available in every service.
  • Return generic error messages. Do not echo stack traces or internal ids to the caller; log the detail on the server.
  • Bind requests to small request models, not to Znode client models or entities, so callers cannot over-post fields you did not intend to accept.
  • Add rate limiting to public and anonymous custom operations, and cap page sizes (for example at most 100 to 500 rows per page).
  • Use HTTPS only and never disable certificate validation. The template already calls UseHttpsRedirection().
  • Read data only from customer-owned tables when you use direct data access. Use Znode APIs for platform data so Znode's own checks apply.

Troubleshooting

SymptomLikely causeFix
401 on every call to the custom routeMissing or expired token; wrong client credentials; the route expects the other auth typeGet a fresh token; check client name and key; check the Authorization scheme (Basic or Bearer)
404 from the gateway for a new custom routeThe route is not registered (no CustomOcelot.json entry, wrong Key, or a method not listed in UpstreamHttpMethod), or the upstream path or downstream host/port is wrongAdd the entry with "Key": "customapi" and the right methods; check the upstream path and the Custom API host and port; redeploy the Custom API
Your endpoint always sees user id 0GatewayIdentityHeadersConfirmed is not set because the section 3.2 check has not passed; the action did not verify the Basic header; called with an application token or Basic without Znode-UserId; or the identity headers are not forwardedRun the check in section 3.2 and set the flag only if it passes; use a user token for user operations; on Basic calls verify the header (section 6.5) and have your server send Znode-UserId
Empty results instead of an errorMissing or wrong Znode-PortalCode on the Znode call (operations that validate it return 400 "Please check the PortalCode." instead)Pass the caller's store to the Znode client; return 403 when no store can be resolved
Admin custom page shows "You are unauthorized to access this resource."ZnodeApiDomainName / ZnodeApiDomainKey (client name and client key) in the Custom API do not match the Admin Console's client credentialsAlign the values (through environment variables) and restart the host
Method Override has no effectReceiver returns 401 (secret mismatch) and Znode falls back to its defaultMake the Admin Console Authorization value and your configured secret identical, including the scheme prefix
Browser reports a CORS errorOrigin not in ZnodeCorsAllowedURLS, or the default policy was removed without RegisterCorsPolicy()Add the exact origin (scheme, host, port) and restart
Custom permission check always deniesPermission not selected for the role, wrong Application Type, or the lookup call failsSelect the permission and save the role; compare PermissionCode exactly; log the lookup status code (not the body)

FAQ

Q: Does the gateway check roles or permissions for my custom route?

No. The gateway authenticates the call and routes it. Role, custom permission, ownership and store checks for a custom operation are your code's job.

Q: Can I add [Authorize] to my controllers instead?

The SDK template's controllers do not use it, and the template relies on the gateway to authenticate callers. If you add ASP.NET Core authorization in the Custom API host, test it with every caller type in section 3.1, including Znode-initiated calls that send your configured Authorization value instead of a JWT.

Q: The Webstore calls my endpoint with Basic credentials. Whose identity is that?

The Webstore's server sends Znode-UserId for the signed-in shopper. Use it only in an action that verifies the Basic header carries your own server's client name and client key (section 6.5), because only your server holds that key. Never base a decision on a Znode-UserId from a call your endpoint did not verify, and do not expose the same action to callers that could set that header themselves.

Q: Should my endpoint return 403 or 404 when a record belongs to someone else?

Return 404 so the response does not confirm that the record exists. Use 403 when the caller is known but the action is not allowed for their role or store.

Q: Do custom permissions hide anything in Znode automatically?

No. Znode stores and returns custom permissions. Your endpoint, page or storefront code must check them.

Q: How do I secure a webhook receiver if Znode cannot sign requests?

Set an Authorization value in Webhook Settings, compare it in constant time in your receiver, use HTTPS, and keep the secret out of the URL and logs.

References

Source articles:


Did you find it helpful? Yes No

Send feedback
Sorry we couldn't be helpful. Help us improve this article with your feedback.