← Back to Snippets
SSJS

Secure a CloudPage for logged in users

Implements a secure OAuth 2.0 Authorization Code flow to protect a Cloud Page. Requires an Installed Package with a "Web App" API Integration in SFMC.Handles token validation, secure cookie sessions, and optional client-side token handoff.


HTML
<script runat="server">
    Platform.Load("core", "1");

    // -----------------------------------------------------------------------
    // PREREQUISITES & SETUP:
    // 1. Setup → Installed Packages → New
    // 2. Add Component → API Integration → Integration Type: Web App
    // 3. Set "Redirect URI" to EXACT CloudPage URL (no mismatched slashes)
    // 4. Anyone with access to the Installed Package can generate tokens
    // -----------------------------------------------------------------------

    // -----------------------------------------------------------------------
    // 1. CONFIGURATION
    // -----------------------------------------------------------------------
    var config = {
        clientId: "YOUR_CLIENT_ID",
        clientSecret: "YOUR_CLIENT_SECRET",
        subdomain: "YOUR_SUBDOMAIN",            // e.g. mc-xxxxxx-xxxx
        redirectUri: "YOUR_CLOUDPAGE_LINK",     // Must match installed package exactly
        cookieName: "App_Auth_Token",

        // SECURITY SETTINGS
        exposeTokenToClient: false,     // Set to true only if client JS must call SFMC APIs
        validateTokenOnLoad: true       // Validate token on page load (safer, adds latency)
    };

    // Auto-constructed OAuth endpoints
    config.authEndpoint     = "https://" + config.subdomain + ".auth.marketingcloudapis.com/v2/authorize";
    config.tokenEndpoint    = "https://" + config.subdomain + ".auth.marketingcloudapis.com/v2/token";
    config.userInfoEndpoint = "https://" + config.subdomain + ".auth.marketingcloudapis.com/v2/userinfo";

    // -----------------------------------------------------------------------
    // 2. CHECK FOR EXISTING SESSION
    // -----------------------------------------------------------------------
    var accessToken = Platform.Request.GetCookieValue(config.cookieName);
    var authCode    = Platform.Request.GetQueryStringParameter("code");

    // -----------------------------------------------------------------------
    // 2.5 VALIDATE EXISTING TOKEN
    // -----------------------------------------------------------------------
    if (accessToken && config.validateTokenOnLoad) {

        try {
            var validateReq = new Script.Util.HttpRequest(config.userInfoEndpoint);
            validateReq.emptyContentHandling = 0;
            validateReq.retries = 2;
            validateReq.continueOnError = true;
            validateReq.contentType = "application/json";
            validateReq.setHeader("Authorization", "Bearer " + accessToken);
            validateReq.method = "GET";

            var validateResp = validateReq.send();

            // Invalid token → regenerate
            if (validateResp.statusCode == 401) {
                accessToken = null;

                // Clear cookie
                Platform.Response.SetCookie(
                    config.cookieName,
                    "",
                    new Date("1970-01-01")
                );
            }
        } catch (e) {
            // Any error → re-authenticate
            accessToken = null;
        }
    }

    // -----------------------------------------------------------------------
    // SCENARIO A: NO TOKEN + NO CODE → Initiate OAuth Login
    // -----------------------------------------------------------------------
    if (!accessToken && !authCode) {
        var authUrl =
            config.authEndpoint +
            "?response_type=code" +
            "&client_id=" + config.clientId +
            "&redirect_uri=" + config.redirectUri;

        Platform.Response.Redirect(authUrl);
    }

    // -----------------------------------------------------------------------
    // SCENARIO B: CODE PRESENT → Exchange for Token
    // -----------------------------------------------------------------------
    if (!accessToken && authCode) {

        var payload = {
            grant_type: "authorization_code",
            code: authCode,
            client_id: config.clientId,
            client_secret: config.clientSecret,
            redirect_uri: config.redirectUri
        };

        try {
            var result = HTTP.Post(
                config.tokenEndpoint,
                "application/json",
                Stringify(payload)
            );

            if (result.StatusCode == 200) {

                var response = Platform.Function.ParseJSON(result.Response[0]);

                // Set cookie (expire in 20 minutes)
                Platform.Response.SetCookie(
                    config.cookieName,
                    response.access_token,
                    new Date(new Date().getTime() + (1000 * 60 * 20))
                );

                // Clear query string
                Platform.Response.Redirect(config.redirectUri);

            } else {
                Write("Error exchanging token: " + result.Response[0]);
            }
        } catch (e) {
            Write("Critical Auth Error: " + Stringify(e));
        }
    }

    // -----------------------------------------------------------------------
    // SCENARIO C: TOKEN OK → Render page & optionally expose to client
    // -----------------------------------------------------------------------
    if (accessToken && config.exposeTokenToClient) {
        Platform.Variable.SetValue("@accessToken", accessToken);
    }

</script>


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Protected Page</title>

    <!--
        CRITICAL NOTE:
        If a user is seeing this HTML, they are authenticated.
        Expired tokens are handled server-side BEFORE this HTML renders.
    -->

    <style>
        body {
            font-family: sans-serif;
            padding: 40px;
            text-align: center;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
        }
    </style>
</head>

<body>

    <div class="container">
        <h1>🔒 Secure Access Granted</h1>
        <p>This content is only visible to authenticated users.</p>
    </div>

    <!-- Optional: Token Handoff to Client -->
    %%[ IF NOT EMPTY(@accessToken) THEN ]%%
        <input type="hidden" id="sfmc-token" value="%%=v(@accessToken)=%%" />
    %%[ ENDIF ]%%

    <script>
        // CLIENT-SIDE SAFETY NET
        const tokenInput = document.getElementById("sfmc-token");
        const token = tokenInput ? tokenInput.value : null;

        // If SSJS says a token exists but JS doesn’t see it → warning
        if (!token && "%%=v(@accessToken)=%%" !== "") {
            console.warn("Token handoff failed.");
        }
    </script>

</body>
</html>