Crownpeak
  • Product Discovery Developer Guide
  • 🛒Item catalog management
    • What is the Items API?
    • How to work with Items
      • Item Schema
        • Attributes
        • Nested Item Schemas
        • Using the Item Schema API
        • DefaultLocale API
        • Onboarding on/migrating to Fredhopper
        • List of Reserved Attributes
      • Category Tree
        • Using the Category Tree API
        • Onboarding on XO
      • Item Catalog
        • Using the Catalog API
      • Items
        • Using the streaming Items API
        • Using the batch Items API
    • Step by Step guide
      • Step by step guide for Fredhopper customers
    • Feedback
      • Using the Feedback API
    • Authorization to APIs
    • Troubleshooting API errors
  • 🎯XO Recommendations
    • Introduction
    • Using the Recommendations API
    • Setting up the Chrome extension
    • Micro-segmentation
    • XO Legacy APIs
  • 🔎XO Search
    • Introduction
    • Getting started
    • API Reference
      • Search API
      • Autocomplete API (Beta)
      • Product Suggest API
    • API Parameters
      • Search
      • Pagination
      • Faceting
      • Sorting
      • Grouping
      • Filtering
      • Disable features
      • Response mask
      • Context
    • Configuration limitation
  • 🧪A/B testing
    • Fredhopper A/B testing
      • Integration steps for a non-caching solution
      • Integration steps for a caching solution
        • Java SDK Integration
          • Setup
          • Retrieve running A/B tests - Java SDK
          • Filter and request variant - Java SDK
          • Extending the SDK
        • Manual A/B tests integration
          • Retrieve running A/B tests
          • Filter out irrelevant A/B tests
          • Assign variants to user
          • Request variant for page
        • Limitations and Best Practices
  • 📚Resources
    • Glossary
    • Best Practices
      • Tracker Best Practices
      • Items API Best Practices
      • Fredhopper Data Configuration Best Practices
      • Fredhopper Query Response Best Practices
      • Fredhopper Merchandising Studio Best Practices
    • Privacy Notice
  • Archived Pages
    • FHR Tracking plan
    • XO Tracking plan
    • The Tracking API and JS Library
      • What to Track
        • Generic Actions
          • View
          • Click
          • Add to Cart
          • Remove from Cart
          • Purchase
        • Custom Actions
      • Initializing the JavaScript Library
      • REST API Technical Documentation
Powered by GitBook
On this page
  • Create a service account
  • Obtaining access tokens
  • Authenticating API calls
  • Access token expiration
  1. Item catalog management

Authorization to APIs

This page describes how to authenticate and authorize your calls to our APIs using standard OpenId Connect

Create a service account

Service accounts provide an identity for your processes to access our APIs. They can authenticate themselves using either a Public Key or Password Authentication.

We recommend that you use Public key authentication which doesn't require sending secrets over the network.

You will need a private key to sign your access token requests, and a corresponding public key that our identity server will use to verify the signature.

Generate an RSA private key

openssl genrsa -des3 -out private.pem 2048

OpenSSL will ask you for a passphrase that will be used to encrypt the private key file.

Generate the corresponding public key

openssl rsa -in private.pem -outform PEM -pubout -out public.pem

Enter the private key passphrase when prompted.

Create the service account

Please reach out to your Technical Consultant to request a service account to be created. Specify that you chose Public Key Authentication and provide your public key. They will give you in return a Client ID and tenant ID that you will need in the following steps.

Please reach out to your Technical Consultant to request a service account to be created. Specify that you chose password authentication. They will provide you with a Client ID, secret and tenant ID that you will need in the following steps.

Obtaining access tokens

Access tokens can be obtained using the OpenId Connect Client Credentials grant.

The token endpoint to use is: https://iam.attraqt.io/auth/realms/${tenantId}/protocol/openid-connect/token where ${tenantId} is the identifier of your Attraqt tenant.

This endpoint is rate-limited at 10 requests per seconds, which is more than enough when tokens are properly cached and reused until expiration. Hitting the rate limit will cause HTTP 429 errors. It is recommended to implement a retry strategy to handle those errors (see also Troubleshooting API errors).

The process differs depending on whether you are using Public Key or Password authentication.

The basic steps are:

    • iss: your client ID (c.f. previous step)

    • sub: also your client ID

    • aud: the token endpoint

    • jti: a uniquely generated ID

    • exp: a rather short expiration time, one minute is more than enough.

  1. Sign the JWT with the private key you generated earlier.

  2. Send a client_credentials grant request to the authorization server token endpoint.

  3. Use the access_token in the response to obtain Requesting Party Tokens that will be needed to authenticate your requests to Attraqt private APIs (see below).

Node.js example

const { promisify } = require('util');
const { readFile } = require('fs');
const { sign } = require('jsonwebtoken');
const uuid = require('uuid');
const request = require('request-promise-native');

// ...

// replace this by the path of the PEM file containing your encrypted private key
// (c.f. "Create a Service Account" section)
const encryptedPrivateKeyPem = await promisify(readFile)('/path/to/my/pkcs8/key.pem', 'utf8');
// replace this by the passphrase you used when generating your private key
const encryptedPrivateKeyPassphrase = 'yourSecretPassphrase'
// replace this by the client ID of your service account
// (c.f. "Create a Service Account" section)
const serviceAccountClientId = 'your-client-id';
// replace this by your Attraqt tenant ID
const tenantId = "myTenantId";
const tokenEnpoint = `https://iam.attraqt.io/auth/realms/${tenantId}/protocol/openid-connect/token`;

const jwt = await promisify(sign)(
    {},
    {
        key: encryptedPrivateKeyPem,
        passphrase: encryptedPrivateKeyPassphrase
    },
    {
        jwtid: uuid.v4(),
        issuer:  serviceAccountClientId,
        subject:  serviceAccountClientId,
        audience:  tokenEnpoint,
        expiresIn:  "1min",
        algorithm:  "RS256"
    }
);

const credentials = await request({
    method: 'POST',
    uri: tokenEnpoint,
    form: {
        grant_type: 'client_credentials',
        client_id: serviceAccountClientId,
        client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
        client_assertion: jwt,
    },
    json: true,
});

const expiresIn = kcCredentials.expires_in; // seconds
const authorizationHeader = `${kcCredentials.token_type} ${kcCredentials.access_token}`;
// Cache the authorization header and use it in your
// calls to Attraqt APIs until its expiration

Java example

To work with the Java SDK, it is easier to convert your private key to the PKCS12 format:

openssl pkcs12 -export -nocerts -inkey private.pem -out key.p12 -name your-key-alias
  • Apache Maven:

<dependency>
  <groupId>com.nimbusds</groupId>
  <artifactId>oauth2-oidc-sdk</artifactId>
  <version>9.2</version>
</dependency>
  • Gradle:

implementation 'com.nimbusds:oauth2-oidc-sdk:9.2'

Sample Code

// replace this by the path of the PKCS12 file containing your private key
File p12File = new File("/path/to/my/pkcs12/key.p12");
// replace this by the passphrase you used when generating your PKCS12 file
char[] p12Passphrase = "yourSecretPassphrase".toCharArray();
// replace this by the key alias you used when generating your PKCS12 file
String keyAlias = "your-key-alias";
// replace this by the client ID of your service account
// (c.f. "Create a Service Account" section)
ClientID serviceAccountClientId = new ClientID("your-client-id");
// replace this by your Attraqt tenant ID
String tenantId = "myTenantId";
URI tokenEnpoint = new URI("https://iam.attraqt.io/auth/realms/master/protocol/"+tenantId+"/token");

KeyStore store = KeyStore.getInstance("PKCS12");
try(InputStream p12stream = new FileInputStream(p12File)){
    store.load(p12stream, p12Passphrase);
}
Key key = store.getKey(keyAlias, p12Passphrase);

HTTPResponse httpResponse = new TokenRequest(
        tokenEnpoint,
        new PrivateKeyJWT(
                serviceAccountClientId,
                tokenEnpoint,
                JWSAlgorithm.RS256,
                (RSAPrivateKey)key,
                null,
                null
        ),
        new ClientCredentialsGrant()
).toHTTPRequest().send();

Object response = OIDCTokenResponseParser.parse(httpResponse);
if(response instanceof OIDCTokenResponse){
    AccessToken accessToken = ((OIDCTokenResponse)response).getOIDCTokens().getAccessToken();
    long expiresIn = accessToken.getLifetime(); // seconds
    String authorizationHeader = accessToken.toAuthorizationHeader();
    // Cache the authorization header and use it in your
    // calls to Attraqt APIs until its expiration
} else {
    String errorDescription = ((TokenErrorResponse)response).getErrorObject().getDescription()
    System.err.println("Error getting access token: " + errorDescription);
}

Service accounts with the "Secret" authentication method can authenticate using basic HTTP authentication, using the client ID as username.

Example using curl:

curl -X POST \
 https://iam.attraqt.io/auth/realms/${tenantId}/protocol/openid-connect/token \
  --user "your-client-id:your-client-secret" \
  --data "grant_type=client_credentials"

The identity server answers with a JSON document containing the following fields:

  • access_token: the access that must be used to authenticate API calls.

  • expires_in: time in seconds before the token expires.

Authenticating API calls

Calls to the Attraqt API must be authenticated with an Authorization header of type Bearer containing the acess token, for example:

curl -x GET \
  https://items.attraqt.io/catalogs/active?tenant=${tenant}&environment=${environment}
  -H "Authorization: Bearer ${access_token}"

You can use the access token as many times as you want before its expiration.

You must reuse access tokens as much as possible because calling the token endpoint is time and resource-consuming.

Access token expiration

Access tokens expire after a time given in the expires_in field of the identity server response. You will then need to get a new one using the same HTTP query.

PreviousUsing the Feedback APINextTroubleshooting API errors

Last updated 1 day ago

Service accounts with the JWT authentication method need to send a JWT signed with their private key to get access tokens, as described in .

Build a with the following claims:

And you can generate JWTs with :

🛒
RFC 7523
JWT
Nimbus OAuth 2.0 SDK