simple-sign-url
v2.0.1
Published
Express library for signing urls and validating them.
Downloads
10
Maintainers
Readme
Simple-Sign-Url
Simple-Sign-Url is a node.js/express library for signing urls and validating them based on secret key.
NOTE You need a Node 10.17.0 and higher.
Init
Install
npm install simple-sign-url
or
yarn add simple-sign-url
Create signature object based on secret.
Secret string should not be known for anyone else, except you
Import
const SignUrl = require('simple-sign-url');
or
import SignUrl = require('simple-sign-url');
Typescript
import SignUrl = require('simple-sign-url');
Alternatively, if --allowSyntheticDefaultImports is turned on, this library can also be imported as a default import:
import SignUrl from 'simple-sign-url';
Using
Create signed url object
const SignUrl = require('simple-sign-url');
const signUrl = new SignUrl(
'your secret key string',
60, // optional (in seconds)
'sha256', // optional
);
Generate signed url
const url = 'http://example.com/resource';
const httpMethod = 'get';
const signedUrl = signUrl.generateSignedUrl(url, httpMethod);
Verify url on resource side using middleware
app.get('/resource', signUrl.verifier(), (req, res, next) => {
res.send('ok');
});
Verify url with custom callbacks
const onInvalid = (req, res, next) => {
console.log('Url is invalid');
res.sendStatus(403);
};
const onExpired = (req, res, next) => {
console.log('Url is expired');
res.sendStatus(410);
};
app.get(
'/resource',
signUrl.verifier(onInvalid, onExpired),
(req, res, next) => {
res.send('ok');
},
);
Verify url in other place using custom object
const resultCode = signUrl.verifySignedUrl({
protocol: 'http',
host: 'localhost:8080',
originalUrl:
'/source/a?signed=e:12343254;m:GET;r:1422553972;e8d071f5ae64338e3d3ac8ff0bcc583bd1d1dsa',
method: 'GET',
});
Example application
const express = require('express');
const SignUrl = require('simple-sign-url');
const SECRET_KEY = 'Sff22dk^:ds';
const signUrl = new SignUrl(SECRET_KEY);
const app = express();
// Index with signed link
app.get('/', (req, res, next) => {
const url = 'http://localhost:8080/source/a';
const httpMethod = 'get';
const signedUrl = signUrl.generateSignedUrl(url, httpMethod);
res.send(signedUrl);
/*
Returns something like
http://localhost:8080/source/a?signed=e:12343254;m:GET;r:1422553972;e8d071f5ae64338e3d3ac8ff0bcc583bd1d1dsa
*/
});
// Validating
app.get('/source/:a', signUrl.verifier(), (req, res, next) => {
res.send(req.params.a);
});
app.listen(8080);
License
MIT