Supporto CWT per le funzioni CloudFront - Amazon CloudFront

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Supporto CWT per le funzioni CloudFront

Questa sezione fornisce dettagli sul supporto per i token Web CBOR (CWT) nelle CloudFront funzioni, che consente l'autenticazione e l'autorizzazione sicure basate su token presso le edge location. CloudFront Questo supporto viene fornito come modulo, accessibile nella funzione. CloudFront

Per utilizzare questo modulo, create una CloudFront funzione utilizzando JavaScript runtime 2.0 e includete la seguente istruzione nella prima riga del codice della funzione:

import cf from 'cloudfront';

I metodi associati a questo modulo sono accessibili tramite (dove* è un jolly che rappresenta le diverse funzioni presenti nel modulo):

cf.cwt.*

Per ulteriori informazioni, consulta Funzionalità di runtime JavaScript 2.0 per Funzioni CloudFront.

Attualmente, il modulo supporta solo la struttura MAC0 con algoritmo HS256 (HMAC-SHA256) con un limite di 1 KB per la dimensione massima del token.

Struttura dei token

Questa sezione illustra la struttura dei token prevista dal modulo CWT. Il modulo si aspetta che il token sia etichettato e identificabile correttamente (ad esempio COSE MAC0). Inoltre, per quanto riguarda la struttura del token, il modulo segue gli standard stabiliti da CBOR Object Signing and Encryption (COSE) [RFC 8152].

( // CWT Tag (Tag value: 61) --- optional ( // COSE MAC0 Structure Tag (Tag value: 17) --- required [ protectedHeaders, unprotectedHeaders, payload, tag, ] ) )
Esempio : CWT utilizza la struttura COSE MAC0
61( // CWT tag 17( // COSE_MAC0 tag [ { // Protected Headers 1: 4 // algorithm : HMAC-256-64 }, { // Unprotected Headers 4: h'53796d6d6574726963323536' // kid : Symmetric key id }, { // Payload 1: "https://iss.example.com", // iss 2: "exampleUser", // sub 3: "https://aud.example.com", // aud 4: 1444064944, // exp 5: 1443944944, // nbf 6: 1443944944, // iat }, h'093101ef6d789200' // tag ] ) )
Nota

Il tag CWT è opzionale per la generazione di token. Tuttavia, il tag di struttura COSE è obbligatorio.

metodo validateToken ()

La funzione decodifica e convalida un token CWT utilizzando la chiave specificata. Se la convalida ha esito positivo, restituisce il token CWT decodificato. Altrimenti, genera un errore. Tieni presente che questa funzione non esegue alcuna convalida sul set di attestazioni.

Richiesta

cf.cwt.validateToken(token, handlerContext{key})
Parameters
token (richiesto)

Token codificato per la convalida. Questo deve essere un JavaScript buffer.

HandlerContext (obbligatorio)

Un JavaScript oggetto che memorizza il contesto per la chiamata validateToken. Al momento, è supportata solo la proprietà key.

chiave (obbligatoria)

Chiave segreta per il calcolo del message digest. Può essere fornita come stringa o JavaScript buffer.

Risposta

Quando il validateToken() metodo restituisce un token convalidato correttamente, la risposta della funzione è a CWTObject nel seguente formato. Una volta decodificate, tutte le chiavi di rivendicazione vengono rappresentate come stringhe.

CWTObject { protectedHeaders, unprotectedHeaders, payload }

Esempio: convalida il token con kid inviato come parte del token

Questo esempio dimostra la convalida del token CWT, in cui il kid viene estratto dall'header. Il bambino viene quindi passato KeyValueStore a CloudFront Functions per recuperare la chiave segreta usata per convalidare il token.

import cf from 'cloudfront' const CwtClaims = { iss: 1, aud: 3, exp: 4 } async function handler(event) { try { let request = event.request; let encodedToken = request.headers['x-cwt-token'].value; let kid = request.headers['x-cwt-kid'].value; // Retrieve the secret key from the kvs let secretKey = await cf.kvs().get(kid); // Now you can use the secretKey to decode & validate the token. let tokenBuffer = Buffer.from(encodedToken, 'base64url'); let handlerContext = { key: secretKey, } try { let cwtObj = cf.cwt.validateToken(tokenBuffer, handlerContext); // Check if token is expired const currentTime = Math.floor(Date.now() / 1000); // Current time in seconds if (cwtObj[CwtClaims.exp] && cwtObj[CwtClaims.exp] < currentTime) { return { statusCode: 401, statusDescription: 'Token expired' }; } } catch (error) { return { statusCode: 401, statusDescription: 'Invalid token' }; } } catch (error) { return { statusCode: 402, statusDescription: 'Token processing failed' }; } return request; }

metodo generateToken ()

Questa funzione genera un nuovo token CWT utilizzando il payload e le impostazioni di contesto fornite.

Richiesta

cf.cwt.generateToken(generatorContext, payload)
Parameters
GeneratorContext (obbligatorio)

Si tratta di un JavaScript oggetto che viene utilizzato come contesto per la generazione del token e contiene le seguenti coppie chiave-valore:

CwtTag (opzionale)

Questo valore è un booleano, che se lo true specifica deve essere aggiunto. cwtTag

CoseTag (obbligatorio)

Specifica il tipo di tag COSE. Attualmente supporta MAC0 solo.

chiave (richiesta)

Chiave segreta per calcolare il message digest. Questo valore può essere una stringa o. JavaScript Buffer

payload (obbligatorio)

Payload di token per la codifica. Il payload deve essere in formato. CWTObject

Risposta

Restituisce un JavaScript Buffer contenente il token codificato.

Esempio : genera un token CWT
import cf from 'cloudfront'; const CwtClaims = { iss: 1, sub: 2, exp: 4 }; const CatClaims = { catu: 401, catnip: 402, catm: 403, catr: 404 }; const Catu = { host: 1, path: 2, ext: 3 }; const CatuMatchTypes = { prefix_match: 1, suffix_match: 2, exact_match: 3 }; const Catr = { renewal_method: 1, next_renewal_time: 2, max_uses: 3 }; async function handler(event) { try { const response = { statusCode: 200, statusDescription: 'OK', headers: {} }; const commonAccessToken = { protected: { 1: "5", }, unprotected: {}, payload: { [CwtClaims.iss]: "cloudfront-documentation", [CwtClaims.sub]: "cwt-support-on-cloudfront-functions", [CwtClaims.exp]: 1740000000, [CatClaims.catu]: { [Catu.host]: { [CatuMatchTypes.suffix_match]: ".cloudfront.net" }, [Catu.path]: { [CatuMatchTypes.prefix_match]: "/media/live-stream/cf-4k/" }, [Catu.ext]: { [CatuMatchTypes.exact_match]: [ ".m3u8", ".ts", ".mpd" ] } }, [CatClaims.catnip]: [ "[IP_ADDRESS]", "[IP_ADDRESS]" ], [CatClaims.catm]: [ "GET", "HEAD" ], [CatClaims.catr]: { [Catr.renewal_method]: "header_renewal", [Catr.next_renewal_time]: 1750000000, [Catr.max_uses]: 5 } } }; if (!request.headers['x-cwt-kid']) { throw new Error('Missing x-cwt-kid header'); } const kid = request.headers['x-cwt-kid'].value; const secretKey = await cf.kvs().get(kid); if (!secretKey) { throw new Error('Secret key not found for provided kid'); } try { const genContext = { cwtTag: true, coseTag: "MAC0", key: secretKey }; const tokenBuffer = cf.cwt.generateToken(commonAccessToken, genContext); response.headers['x-generated-cwt-token'] = { value: tokenBuffer.toString('base64url') }; return response; } catch (tokenError) { return { statusCode: 401, statusDescription: 'Could not generate the token' }; } } catch (error) { return { statusCode: 402, statusDescription: 'Token processing failed' }; } }
Esempio : Aggiorna il token in base a una logica
import cf from 'cloudfront' const CwtClaims = { iss: 1, aud: 3, exp: 4 } async function handler(event) { try { let request = event.request; let encodedToken = request.headers['x-cwt-token'].value; let kid = request.headers['x-cwt-kid'].value; let secretKey = await cf.kvs().get(kid); // Retrieve the secret key from the kvs // Now you can use the secretKey to decode & validate the token. let tokenBuffer = Buffer.from(encodedToken, 'base64url'); let handlerContext = { key: secretKey, } try { let cwtJSON = cf.cwt.validateToken(tokenBuffer, handlerContext); // Check if token is expired const currentTime = Math.floor(Date.now() / 1000); // Current time in seconds if (cwtJSON[CwtClaims.exp] && cwtJSON[CwtClaims.exp] < currentTime) { // We can regnerate the token and add 8 hours to the expiry time cwtJSON[CwtClaims.exp] = Math.floor(Date.now() / 1000) + (8 * 60 * 60); let genContext = { coseTag: "MAC0", key: secretKey } let newTokenBuffer = cf.cwt.generateToken(cwtJSON, genContext); request.headers['x-cwt-regenerated-token'] = newTokenBuffer.toString('base64url'); } } catch (error) { return { statusCode: 401, statusDescription: 'Invalid token' }; } } catch (error) { return { statusCode: 402, statusDescription: 'Token processing failed' }; } return request; }