Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
console.log(JSON.stringify(request));
const parsedCookies = parseCookies(request.headers);
if (parsedCookies && parsedCookies['londonsheriff-Token'] && request.uri == "/articles") {
console.log('Cookie present');
const jwtToken = parsedCookies['londonsheriff-Token'];
const b64string = config.web.base64SigningKey;
const verifiedToken = nJwt.verify(jwtToken, b64string);
// TODO: Decide what to do when the passed token is not valid or expired
const userDetails = jwtToken.split('.')[1];
console.log(userDetails);
console.log(Buffer.from(userDetails, 'base64').toString('ascii'));
let userToken = JSON.parse(Buffer.from(userDetails, 'base64').toString('ascii'));
const userName = userToken.sub;
const scope = userToken.scope;
let templateUrl = TEMPLATE_URL;
http.get(templateUrl, (res) => {
var content = '';
res.on('data', (chunk) => { content += chunk; });
res.on('end', () => {
if(typeof user !== 'undefined') {
if (!user.authenticated) {
responseStatus = 401;
responseBody = {'error':{'code':responseStatus,'message':'Unauthorized'}};
} else {
let claims = {
iss: ROOT_PATH, // The URL of your service
sub: user.userId, // The UID of the user in your system
scope: user.entitlement
};
//console.log(base64SigningKey);
try {
let jwt = nJwt.create(claims,signingKey);
// console.log(`jwt: ${jwt}`);
let token = jwt.compact();
console.log(`token: ${token}`);
let responseAuthorization = `Bearer ${token}`;
res.setHeader('Authorization', responseAuthorization);
// HTTP-only cookies aren't accessible via JavaScript through the Document.cookie property.
res.setHeader('Set-Cookie',`londonsheriff-Token=${token}; HttpOnly; Path=/`); // Non-production
// A secure cookie will only be sent to the server when a request is made using SSL and the HTTPS protocol.
//res.setHeader('Set-Cookie',`londonsheriff-Token=${token}; Secure; HttpOnly; Path=/`); // TODO: Production
responseStatus = 200;
responseBody = claims;
} catch (error) {
responseStatus = 403;
responseBody = {'error':{'code':responseStatus,'message':'Forbidden','details':error.message}};
console.log(error);
}
function getTokenResource(compactToken, callback) {
nJwt.verify(compactToken, jwtSigningKey, function (err, parsedToken) {
if (err) {
return callback(); // Ignore failure, means token is already invalid
}
var tokenType = parsedToken.header.stt;
var tokenId = parsedToken.body.jti;
loadTokenForUser(tokenId, tokenType, callback);
});
}
module.exports = function exchangeStormpathToken(req, account, callback) {
var config = req.app.get('stormpathConfig');
var application = req.app.get('stormpathApplication');
var apiKey = config.client.apiKey;
var payload = {
sub: account.href,
iat: new Date().getTime() / 1000,
iss: application.href,
status: 'AUTHENTICATED',
aud: apiKey.id
};
var token = nJwt.create(payload, apiKey.secret, 'HS256');
// Token is only used for exchanging an OAuth token.
// For that reason, we set a very low expiration (1min).
token.setExpiration(new Date().getTime() + (60 * 1000));
var authenticator = new stormpath.OAuthStormpathTokenAuthenticator(application);
var options = {
stormpath_token: token.compact()
};
authenticator.authenticate(options, function errorLogger() {
if (arguments[0] !== null) {
var logger = req.app.get('stormpathLogger');
logger.info('Token exchange failed', arguments[0]);
}
},function(err, value){
result = [err, value];
decodedAccessToken = nJwt.verify(
result[1].tokenResponse.access_token,
client._dataStore.requestExecutor.options.client.apiKey.secret,
'HS256'
);
var requestedScopes = requestedScope.split(' ');
assert.equal(scopeFactoryArgs[1][0], requestedScopes[0]);
assert.equal(scopeFactoryArgs[1][1], requestedScopes[1]);
done();
});
});
it('should set req.organization from the access token value', function (done) {
var apiKey = stormpathApplication.dataStore.requestExecutor.options.client.apiKey.secret;
var cookieName = fakeConfig.web.accessTokenCookie.name;
var mockPayload = {
org: stormpathOrganization.href
};
var mockCookieJwt = nJwt.create(mockPayload, apiKey, 'HS256');
mockCookieJwt.header.kid = 'f8fdb5c5-6e04-42db-85d8-47b1773c83d0';
request(expressApp)
.get('/')
.set('Host', stormpathOrganization.nameKey + '.localhost.com')
.set('Cookie', [cookieName + '=' + mockCookieJwt.toString()])
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
var result = JSON.parse(res.text);
assert(!!result);
assert(!!result.organization);
describe('posting a spoofed brearer token',function(){
var fakeToken = nJwt.Jwt({
sub: 'me'
}).signWith('HS256','my fake key').compact();
it('should error',function(done){
request(app)
.post(protectedEndpoint)
.set('Authorization', 'Bearer ' + fakeToken)
.send(postData)
.expect(401,{errorMessage:jwtErrors.SIGNATURE_MISMTACH},done);
});
});
describe('posting an expired brearer token',function(){
it('should error',function(done){
request(app)
.post(protectedEndpoint)
.set('Authorization', 'Bearer ' + expiredToken)
.send(postData)
.expect(401,{errorMessage:jwtErrors.EXPIRED},done);
});
});
it('should error',function(done){
request(app)
.post(protectedEndpoint)
.set('Authorization', 'Bearer ' + fakeToken)
.send(postData)
.expect(401,{errorMessage:jwtErrors.SIGNATURE_MISMTACH},done);
});
});
builder.build(options, function (err, resultUrl) {
assert.isNull(err);
assert.isOk(resultUrl);
var parsedUrl = url.parse(resultUrl, true);
var secret = application.dataStore.requestExecutor.options.client.apiKey.secret;
assert.isDefined(parsedUrl.query.accessToken);
var jwt = nJwt.verify(parsedUrl.query.accessToken, secret);
assert.equal(jwt.body.cb_uri, options.cb_uri);
assert.equal(jwt.body.onsk, options.onsk);
assert.equal(jwt.body.ash, options.ash);
assert.equal(jwt.body.state, options.state);
done();
});
});