Skip to content

Commit

Permalink
Node.js javascript example (#19)
Browse files Browse the repository at this point in the history
* now with Javascript code

* navigation link fixed

* markdown fixed
  • Loading branch information
fbitti committed Mar 29, 2022
1 parent 0206da1 commit f78acae
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
Tokens give you the ability to create URLs that expire. If you only want to give a particular user access to a link for a specific amount of time, you'll need tokens. They're commonly used to secure video assets, but you can create and validate signatures to be transferred in other ways, like cookies or authentication headers.

#### Table of Contents

- How to enable Token Authentication feature
* [VCL](#vcl)
- How to use
Expand All @@ -16,6 +17,7 @@ Tokens give you the ability to create URLs that expire. If you only want to give
* [C#](#c)
* [Java](#java)
* [Rust](#rust)
* [Javascript (Node.js)](#javascript-nodejs)

#### VCL

Expand Down Expand Up @@ -333,8 +335,31 @@ fn main() {
}
```

##### Javascript (Node.js)

```javascript
// a similar example can be tested and remixed at https://javascript-token-fastly.glitch.me/

var crypto = require('crypto');

var path = "/foo/bar.html";

var base64Key = 'iqFPeN2u+Z0Lm5IrsKaOFKRqEU5Gw8ePtaEkHZWuD24=';
// The Buffer.from method decodes a base-64 encoded string.
// Attention: don't convert key to a String or it may not work
var key = Buffer.from(base64Key, 'base64');

// 1,209,600 seconds = 2 weeks
var token_lifetime = 1209600;
// Date.now() gives the current time with a millisecond precision
var expiration = Math.round(Date.now()/1000 + token_lifetime);

var string_to_sign = path + String(expiration);

// calculate the token and convert to HEX
var signature = crypto.createHmac('sha1', key).update(string_to_sign).digest('hex');

var token = String(expiration) + "_" + signature;

console.log("Token:", token);
```

0 comments on commit f78acae

Please sign in to comment.