Custom Endpoint Authentication for Marketing Cloud Documentation

Custom Endpoint Authentication for Marketing Cloud Documentation
Home Page

Custom Endpoint Authentication for Marketing Cloud

Introduction

Welcome to the Custom Endpoint Authentication for Marketing Cloud. This comprehensive guide will walk you through the process of securing your Marketing Cloud API by implementing a custom authentication mechanism. With custom authentication, you can design and tailor the authentication process to meet the unique security requirements of your Marketing Cloud applications and ensure the integrity of data exchanged.

Table of Contents

  1. Overview
  2. Prerequisites
  3. Why Choose Custom Endpoint Authentication for Marketing Cloud?
  4. Implementing Custom Endpoint Authentication
    1. Step 1: Define the Authentication Method
    2. Step 2: Implement Authentication Logic
    3. Step 3: Generate and Validate Authentication Tokens
  5. Securing Marketing Cloud Endpoints
    1. Step 4: Protecting Sensitive Endpoints
    2. Step 5: Error Handling for Authentication Failures
    3. Step 6: Rate Limiting and Additional Security Measures
  6. Conclusion

1. Overview

In this section, we'll provide an overview of the importance of securing your Marketing Cloud API and the advantages of using a custom endpoint authentication approach. You'll gain an understanding of the benefits that custom authentication brings to your Marketing Cloud applications.

Advantages of Using a Custom Endpoint Authentication Approach

The traditional method of authenticating API requests typically involves using a username and password, API keys, or OAuth tokens. While these methods can be secure when implemented correctly, they may not provide the level of control and security required for certain business scenarios. Here's where a custom endpoint authentication approach comes into play.

A custom endpoint authentication approach involves creating your own authentication mechanism for the API endpoints. This method provides several advantages, including:

  1. Enhanced Security: By designing a custom authentication method, you have more control over how authentication is handled. This control enables you to implement additional security layers, such as multi-factor authentication or IP whitelisting, to ensure that only authorized users and systems can access your API.
  2. Reduced Dependency on Default Methods: While the Marketing Cloud API offers standard authentication methods, using a custom approach reduces your dependency on these default methods. This can be beneficial when you want to limit access or tailor authentication specifically to your application's needs.
  3. Flexibility and Customizability: With a custom approach, you have the flexibility to adapt authentication mechanisms as your business requirements change. It allows you to adjust security protocols based on evolving threats or compliance standards.
  4. Integration with Existing Systems: If you already have authentication systems in place for other parts of your infrastructure, a custom endpoint authentication approach can help ensure a unified and coherent security strategy.
  5. Better User Experience: Depending on the implementation, custom authentication may result in a smoother and more seamless user experience, as you can design authentication flows tailored to your users' needs.
  6. Monitoring and Logging: Custom authentication allows you to have more comprehensive monitoring and logging capabilities, enabling you to track and analyze API usage and potential security incidents effectively.

Overall, adopting a custom endpoint authentication approach for your Marketing Cloud API empowers you to bolster security, tailor authentication to your specific requirements, and stay one step ahead of potential threats. However, it's essential to design and implement the custom approach carefully, following security best practices and regularly updating it to maintain a robust and secure marketing infrastructure.

2. Prerequisites

Before diving into custom endpoint authentication for Marketing Cloud, ensure that you have a basic understanding of Marketing Cloud concepts, API integration, and security best practices. Familiarity with authentication methods and protocols will also be beneficial.

3. Why Choose Custom Endpoint Authentication for Marketing Cloud?

Here, we'll discuss the reasons why custom endpoint authentication is a suitable approach for securing your Marketing Cloud API. We'll explore scenarios where standard authentication methods may not fully meet your specific needs and how custom authentication addresses these challenges.

A. Compliance and Regulatory Requirements:

Some industries and regions have specific data privacy and security regulations that necessitate custom authentication approaches. By implementing custom authentication, you can align your Marketing Cloud API with these requirements, helping your organization stay compliant with relevant laws and regulations.

B. User Experience:

Custom endpoint authentication allows you to design a user-friendly login process that aligns with your brand and user interface. This can lead to a better overall user experience, fostering customer trust and loyalty.

C. Token Management and Expiration:

With custom authentication, you have the flexibility to define token management and expiration policies. This means you can set specific token lifetimes and manage token revocation as needed, enhancing security and access control.

D. Scalability:

Custom endpoint authentication can be designed to handle high volumes of API requests efficiently. By optimizing the authentication process to suit your organization's needs, you can ensure that your Marketing Cloud API remains responsive and scalable as your user base grows.

E. IP Whitelisting and Blacklisting:

Some organizations may require IP whitelisting or blacklisting to control access to their Marketing Cloud API. Custom authentication allows you to implement such controls based on your specific requirements.

F. Audit Trail and Monitoring:

With custom authentication, you can design and implement detailed logging and monitoring capabilities. This enables you to track API usage, identify potential security issues, and maintain a comprehensive audit trail for compliance purposes.

G. Custom Business Logic:

In certain scenarios, organizations may need to apply custom business logic during the authentication process. Custom endpoint authentication empowers you to incorporate such logic seamlessly into the authentication flow.

While custom endpoint authentication offers numerous benefits, it's essential to consider the potential challenges and complexities associated with implementing and maintaining a custom solution. Organizations must strike a balance between security, usability, and scalability while carefully considering the resources and expertise required to maintain a robust authentication system. Always weigh the specific needs and objectives of your organization before choosing a particular authentication approach for your Marketing Cloud API.

4. Implementing Custom Endpoint Authentication

This section will guide you through the step-by-step process of implementing custom endpoint authentication for Marketing Cloud. We'll cover the three crucial steps to design and deploy your custom authentication mechanism:

  1. Step 1: Define the Authentication Method - Choose the most suitable authentication method, such as HMAC, JWT, or custom tokens, based on your security requirements.
  2. Step 2: Implement Authentication Logic - Develop the authentication logic to validate incoming requests and ensure the authenticity of clients.
  3. Step 3: Generate and Validate Authentication Tokens - If you opt for token-based authentication, learn how to generate and validate tokens to secure your Marketing Cloud API.
You can review these steps in this blog

5. Securing Marketing Cloud Endpoints

In this section, we'll focus on securing specific endpoints within Marketing Cloud. You'll discover how to apply your custom authentication logic to protect sensitive endpoints and how to handle authentication errors gracefully. Additionally, we'll discuss the importance of implementing rate limiting and other security measures to safeguard against potential attacks.

Access Token Validation Documentation


 /**
* ValidateAuthorization function checks the validity of the provided access token.
*
* @param {string} accessToken - The access token to be validated.
* @returns {object} - If the accessToken is missing or invalid, it returns an error object:
*   { "Error": "Not Authorized. Please validate your access token." }
*   Otherwise, it retrieves data from the "TokenRequests" Data Extension based on the access token.
*   If the Data Extension query returns no results, it also returns the same error object.
*   If the access token is valid and corresponds to a record in the Data Extension, it returns the dataSet object.
*   The dataSet object contains the data retrieved from the "TokenRequests" Data Extension.
*   Note: The structure of dataSet may vary depending on the data extension schema and data present.
*/
function ValidateAuthorization(accessToken) {
if (!accessToken) {
 return { "Error": "Not Authorized. Please validate your access token." };
}
            
var bearerToken = accessToken.split(" ");
var leftOperand = SimpleFilter("access_token", "equals", bearerToken[1]);
var rightOperand = SimpleFilter("token_type", "equals", bearerToken[0]);
var filter = ComplexFilter(leftOperand, "AND", rightOperand);
            
 var dataExtensionProps = {
 "Init": "TokenRequests",
"Filter": filter
};
var dataSet = DataExtensionRowsRetrieve(dataExtensionProps, errorLogDEInit);
            
if (!dataSet || dataSet.length === 0) {
return { "Error": "Not Authorized. Please validate your access token." };
}
            
var currentDate = new Date();
var expirationDate = new Date(dataSet[0].ExpirationDate);
            
if (currentDate > expirationDate)
return { "error": 401, "message": "Token has expired" };
            
return dataSet;
}
                    

Code Explanation:

  • The ValidateAuthorization function takes an accessToken as input to check its validity.
  • If the accessToken is missing or invalid (falsy), the function returns an error object with the message "Not Authorized. Please validate your access token."
  • The access token is split into two parts: the "bearer" token and the actual token. The function assumes the access token is formatted as "Bearer <token>", where "<token>" represents the actual token.
  • The function constructs a filter using the SimpleFilter and ComplexFilter functions to query the "TokenRequests" Data Extension based on the access token.
  • Data Extension properties are set up for retrieving data using the DataExtensionRowsRetrieve function.
  • The function retrieves data from the "TokenRequests" Data Extension based on the provided filter.
  • If the Data Extension query returns no results (no data or a valid record is not found), the function returns the same error object as before, indicating that the user is not authorized.
  • The function compares the current date with the expiration date obtained from the Data Extension record. If the current date is greater than the expiration date, it returns an error object with a 401 status code, indicating that the token has expired.
  • If the access token is valid and has not expired, the function returns the dataSet object containing the data retrieved from the "TokenRequests" Data Extension. The structure of dataSet may vary depending on the data extension schema and data present.

Complex Filter Function Documentation


/**
* This function creates a complex filter object with a left operand, logical operator, and right operand.
*
* @param {string} leftOperand - The left operand of the complex filter.
* @param {string} simpleOperator - The logical operator used in the complex filter.
* @param {string} rightOperand - The right operand of the complex filter.
* @returns {Object} - A complex filter object containing the left operand, logical operator, and right operand.
*/
function ComplexFilter(leftOperand, simpleOperator, rightOperand) {
// The function returns an object representing the complex filter.
return {
LeftOperand: leftOperand,         // The left operand of the complex filter.
LogicalOperator: simpleOperator,  // The logical operator used in the complex filter.
RightOperand: rightOperand        // The right operand of the complex filter.
 };
}
                    

Code Explanation:

The ComplexFilter function is used to create a complex filter object that represents a filter condition in data processing.

  • leftOperand: The left side of the filter condition. It could be a field name, a property, or any data value that you want to compare.
  • simpleOperator: The logical operator used in the filter condition. It represents how the leftOperand and rightOperand are related. Examples of logical operators are "equals," "greater than," "less than," "contains," etc.
  • rightOperand: The right side of the filter condition. It is the value you want to compare with the leftOperand.
  • The function returns an object containing three properties: LeftOperand, LogicalOperator, and RightOperand. This object represents a complete complex filter.

GetJWT Function

Generates a JSON Web Token (JWT) from the provided JSON payload using a predefined key and algorithm.

Explanation:

The function GetJWT is defined with two parameters: postData (the JSON payload) and errorLogDEInit (the name of the Data Extension for logging exceptions).

Inside the function, the provided JSON payload (postData) is stored in a variable called @JSON using Variable.SetValue("@JSON", postData).

Next, an AMPscript block is defined and stored in the variable ampScriptBlock. AMPscript is a scripting language used in the context of Salesforce Marketing Cloud and is denoted by the %%[ ... ]%% syntax. The AMPscript block calls a function named GetJWT with the parameters 'JWT Signing Secret', 'HS256', and @JSON. It seems like this AMPscript function is used to generate the actual JWT and store it in a variable called @JWT.

Platform.Function.TreatAsContent(ampScriptBlock) is used to process and execute the AMPscript block.

After executing the AMPscript block, the generated JWT is retrieved from the @JWT variable using Variable.GetValue('@JWT'), and it is returned as the result of the GetJWT function.

If any exception occurs during the JWT generation process, the catch block is triggered. The exception details are logged into a Data Extension with the name provided in the errorLogDEInit parameter. The exception message, description, inner exception (if available), and the name of the function where the exception occurred ("GetJWT") are stored as a row in the Data Extension.

After logging the exception, the throw ex; statement is used to rethrow the exception, propagating it to the caller of the GetJWT function.

Access Token Validation - Server-Side Script

Script Description:
This is a server-side script that validates an access token retrieved from the request header. It uses a custom ValidateAuthorization function to check the token's validity by querying the "TokenRequests" Data Extension. If the access token is valid, it returns the data from the Data Extension. Otherwise, it logs the error details and returns an error response as a string.

Server-Side Script:


<script runat="server">
Platform.Load("core", "1");
  var errorLogDEInit="Akamai_Error_Log";
  // Main Block
  try {
    // Retrieve the access token from the request header
    var accessToken = Platform.Request.GetRequestHeader("Authorization");
    var postData=Platform.Request.GetPostData();
    // Initialize the HTTPProperties Data Extension and add a row with request information
    var HTTPPropertiesDE = DataExtension.Init("HTTPProperties");
    HTTPPropertiesDE.Rows.Add({
      Browser: Platform.Request.Browser,
      ClientIP: Platform.Request.ClientIP,
      HasSSL: Platform.Request.HasSSL,
      IsSSL: Platform.Request.IsSSL,
      Method: Platform.Request.Method,
      QueryString: Platform.Request.QueryString,
      ReferrerURL: Platform.Request.ReferrerURL,
      RequestURL: Platform.Request.RequestURL,
      UserAgent: Platform.Request.UserAgent
    }
                             );
    if (Platform.Request.Method == "GET") {
      // If the HTTP method is GET, return a "403 Forbidden" message
      var response = {
        "message": "403 Forbidden"};
      // Output the response as a string
      Write(Stringify(response));
    }
    else {
      // Validate the access token using the previously defined ValidateAuthorization function
      // The response object will contain either the data from the TokenRequests Data Extension or an error message
      var response = ValidateAuthorization(accessToken);
      if(postData){
        var jwt=GetJWT(postData,errorLogDEInit);
        var token={
          "JWT":jwt};
        var cookie=Platform.Response.SetCookie("JWT",Stringify(token),new Date(),true);
      }
      // Output the response as a string
      if(postData && response.code==200)
        Write(Stringify(token));
      else
        Write(Stringify(response));
    }
  }
  catch (ex) {
    // Exception handling: Log the error details into the errorLogDEInit Data Extension
    var APIExceptionDE = DataExtension.Init(errorLogDEInit);
    APIExceptionDE.Rows.Add({
      Message: ex.message,
      Description: ex.description,
      InnerException: ex.jintException,
      FunctionName: "Main Block"
    }
                           );
    // Return an error response as a string in case of an exception
    var response = {
      "Error": ex.message};
    Write(Stringify(response));
  }
</script>

Note:
In this script, the Platform.Load function is used to load the core module for Server-Side JavaScript (SSJS) in the Salesforce Marketing Cloud environment.

6. Conclusion

Thank you for choosing the Custom Endpoint Authentication for Marketing Cloud Documentation. Let's begin securing your Marketing Cloud API with confidence!



Comments


Knowledge Article

Most Viewed

CLOUD PAGE ENABLEMENT - PART 1

EMAIL NOT SENT IN JOURNEY BUILDER

CONSIDERATIONS FOR JOURNEY BUILDER

Journey Builder REST API Documentation

Preference Center Demystified

Popular Posts

CLOUD PAGE ENABLEMENT - PART 1

EMAIL NOT SENT IN JOURNEY BUILDER

CONSIDERATIONS FOR JOURNEY BUILDER

Journey Builder REST API Documentation

Preference Center Demystified

SEND LOG EANBLEMENT

Share with Friends

Disclaimer:

The information provided on this technical blog is for general informational purposes only. As a SFMC (Salesforce Marketing Cloud) Technical Architect, I strive to offer accurate and up-to-date content related to SFMC and its associated technologies. However, please note that technology is constantly evolving, and the information provided may become outdated or inaccurate over time.

The content published on this blog represents my personal views and experiences as a SFMC Technical Architect and does not necessarily reflect the official views or opinions of any organization or employer I may be affiliated with.

While I make every effort to ensure the accuracy and reliability of the information presented, I cannot guarantee its completeness, suitability, or applicability to your specific circumstances. Therefore, it is essential to verify any information provided and make your own independent assessments or seek professional advice if needed.

Furthermore, any actions taken based on the information provided on this blog are at your own risk. I shall not be held liable for any damages, losses, or inconveniences arising from the use of the information presented here.

Please keep in mind that SFMC and its associated technologies are complex and require technical expertise for proper implementation and management. It is recommended to consult with qualified professionals or official SFMC documentation for comprehensive guidance.

Finally, please note that any product or company names mentioned on this blog are trademarks or registered trademarks of their respective owners. The mention of these trademarks or registered trademarks does not imply any endorsement or affiliation with the blog.

By accessing and using this blog, you agree to the terms of this disclaimer. If you do not agree with any part of this disclaimer, please refrain from using this blog.