What is the best way to obtain a signed cookie in aws-sdk-js-v3?

I am looking to utilize signed cookies for accessing private content stored on S3 using CloudFront for CDN.

I am struggling to identify the appropriate commands to generate signed cookies in aws-sdk-js-v3. According to the updated SDK documentation, it should resemble the second code snippet below, but I am unable to locate the specific npm package that contains the necessary commands. In the previous version (v2), it was "getSignedCookie" but I am uncertain of its updated equivalent.

Previous version (v2):

import AWS from "aws-sdk";

const CFSigner = new AWS.CloudFront.Signer(cfPublicKeyId, cfPrivateKey);
const policy = JSON.stringify({
        Statement: [
          {
            Resource: `https://${cfDomain}/images/*`,
            Condition: {
              DateLessThan: {
                "AWS:EpochTime": expireTime,
              },
            },
          },
        ],
      });

const myCookie = CFSigner.getSignedCookie({ policy });

Attempt using v3 SDK

import {
  CloudFrontClient,
  CloudFrontClientConfig,
} from "@aws-sdk/client-cloudfront";
import { ICantFindAnAppropriateCommandToSignCookies } from "ICantFindAnAppropriateCommandToSignCookies";

async function signMyCookies() {
  const config: CloudFrontClientConfig = {
    apiVersion: "2015-12-08",
    credentials: {
      accessKeyId: process.env.SC_ADMIN_ACCESS_KEY_ID,
      secretAccessKey: process.env.SC_ADMIN_SECRET_ACCESS_KEY,
    },
    region: "us-east-01",
  };

  const cfClient = new CloudFrontClient(config);

  const cfDomain = process.env.CLOUDFRONT_DOMAIN;

  const twoDays = 2 * 24 * 60 * 60 * 1000;

  const expireTime = Math.floor((Date.now() + twoDays) / 1000);

  const params = {
    policy: JSON.stringify({
      Statement: [
        {
          Resource: `https://${cfDomain}/images/*`,
          Condition: {
            DateLessThan: {
              "AWS:EpochTime": expireTime,
            },
          },
        },
      ],
    }),
  };

  const command = new ICantFindAnAppropriateCommandToSignCookies(params);

  try {
    const data = await cfClient.send(command);
    console.log("SUCCESS!", data);
  } catch (error) {
    console.error("OH NO ERROR GETTING SIGNED COOKIE", error);
  } finally {
    console.log("PROCESS COMPLETE");
  }
}

Answer №2

If you're looking for information in the future, I came across this helpful resource on AWS SDK CloudFront Signer

It mentions the library @aws-sdk/cloudfront-signer, which includes useful methods like getSignedCookies()

This library could be a useful tool to implement.

In case the link becomes unavailable, here is a snippet of example code from the mentioned resource:

const { getSignedCookies } = require("@aws-sdk/cloudfront-signer"); // CJS

const cloudfrontDistributionDomain = "https://d111111abcdef8.cloudfront.net";
const s3ObjectKey = "private-content/private.jpeg";
const url = `${cloudfrontDistributionDomain}/${s3ObjectKey}`;
const privateKey = "CONTENTS-OF-PRIVATE-KEY";
const keyPairId = "PUBLIC-KEY-ID-OF-CLOUDFRONT-KEY-PAIR";
const dateLessThan = "2022-01-01";

const cookies = getSignedCookies({
  url,
  keyPairId,
  dateLessThan,
  privateKey,
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The downloaded zip file appears to be corrupt and cannot be opened

As a newcomer to TypeScript, I embarked on creating a simple function to download a zip file. This is the code I've managed to put together: import fs from 'fs'; import https from 'https'; export function handler(): void { https ...

Verify that each interface in an array includes all of its respective fields - Angular 8

I've recently created a collection of typed interfaces, each with optional fields. I'm wondering if there is an efficient method to verify that all interfaces in the array have their fields filled. Here's the interface I'm working wit ...

Error message: "The toJSON method is not found for the item in the nested array of

Encountering an issue with NSwag in my Angular project where it throws an error when attempting to send data if the object contains a nested array of objects like this: export interface IJobAdDto { mainJobAd: JobAddDetailsDto; differentLanguageJobA ...

The variable "$" cannot be found within the current context - encountering TypeScript and jQuery within a module

Whenever I attempt to utilize jQuery within a class or module, I encounter an error: /// <reference path="../jquery.d.ts" /> element: jQuery; // all is good elementou: $; // all is fine class buggers{ private element: jQuery; // The nam ...

Navigating through Objects in Angular 9

I am facing a challenge in Angular 9/Typescript while trying to iterate through the object response from my JSON data. Despite searching for solutions, I haven't found any that work for me. In my JSON, there is a section called "details" which contain ...

Button for enabling and disabling functionality, Delete list in Angular 2

I am looking to toggle between the active and inactive classes on a button element. For example, in this demo, there are 5 buttons and when I click on the first button it removes the last one. How can I remove the clicked button? And how do I implement the ...

What is the best way for me to generate a fresh object?

In one of my components, I have implemented a feature where clicking on an image toggles a boolean variable to show or hide a menu. The HTML structure for this functionality is as follows: <img src="../../assets/image/dropdown.png" class="dropdown-imag ...

Sharing information between Angular components

Having recently started using Angular, I'm facing an issue with passing an array to a different component that is not parent or child related. What I aim to achieve is: upon selecting rows from the first component table, a new view should open up disp ...

The Angular 11 library module has been successfully imported into the consuming app but it is not being utilized

Currently, I am in the process of creating an Angular library that will encompass services, pipes, and directives to be utilized across various Angular projects within my organization. At this point, I have successfully implemented three services within th ...

Having trouble with a tslint error in Typescript when creating a reducer

I encountered an error while working with a simple reducer in ngRx, specifically with the on() method. https://i.sstatic.net/9fsvj.png In addition, I came across some errors in the reducer_creator.d.ts file: https://i.sstatic.net/sWvMu.png https://i.ss ...

Drawing a real-time curve using Phaser 3

After reading the article at the following link, I am attempting to create a dynamic curve showing where a bullet intersects with the land in my game before firing. Any suggestions or ideas on how to achieve this would be greatly appreciated. Thank you. L ...

Show the interface value for an array type

I have created a component to display API data. The structure of the component is as follows: HTML: <div *ngFor="let customer of customers"> <p>Name: {{customer?.name}}</p <p>Phone: {{customer?.phoneNumbers}}</p </div&g ...

Is seamless integration possible between Angular2 and jQuery plugins?

When attempting to integrate jQuery plugins with Angular 2, there are three distinct scenarios: 1. ONLOAD: Initializing the plugin on page load works smoothly with the following code snippet: ngAfterViewChecked(){ ... $('#somedatatable1&apos ...

Separate an array in TypeScript based on the sign of each number, and then replace the empty spaces with null objects

Hey, I'm facing a little issue, I have an Array of objects and my goal is to split them based on the sign of numbers. The objects should then be dynamically stored in different Arrays while retaining their index and getting padded with zeros at the b ...

Decrease the construction duration within a sprawling Angular 8 project

It takes nearly 10-15 minutes to compile the project in production mode, resulting in a dist folder size of 32MB Here are the production options I am currently using:- "production": { "optimization": true, "outputHashing": "all", ...

Angular: Enable function to await Observable completion before returning result

I require assistance with the user function below: getUser(uuid: string): Observable<WowUserDataModel> { let user: WowUserDataModel = { login: null, userUuid: uuid, firstName: null, lastName: null, displayName: nul ...

Is there a way to transfer a variable from Angular 2 Frontend Express JS to an Angular 2 component?

After conducting thorough research, I have made specific modifications to my code. However, I am encountering some errors in my console that I cannot seem to resolve. Despite following a tutorial step by step. Your assistance would be highly valued as I a ...

Unable to store object data within an Angular component

This is a sample component class: export class AppComponent { categories = { country: [], author: [] } constructor(){} getOptions(options) { options.forEach(option => { const key = option.name; this.categories[k ...

Transform the `PascalCase` format into `strictCamelCase` in TypeScript type conversion

By utilizing the built-in Uncapitalize<S> function, you can easily convert a string like FooBar to fooBar: const fooBar: Uncapitalize<'FooBar'> = 'fooBar'; However, this method proves inadequate when dealing with class name ...

Steps for utilizing a Get() method to view a response within Angular

I am having trouble with implementing an API call on a page and I'm unsure about what's wrong with the Subscribe/Observe method. Currently, this is the code that I have: import { Component, OnInit } from '@angular/core'; import { Ro ...