Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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);
}
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]);
}
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);
before(function(done){
newAccount = helpers.fakeAccount();
unsignedToken = nJwt.create({hello:'world'},'not a secret').compact();
helpers.createApplication(function(err,app){
if(err){
done(err);
}else{
application = app;
expiredToken = nJwt.create(
{hello:'world'},
application.dataStore.requestExecutor.options.client.apiKey.secret
).setExpiration(new Date().getTime())
.compact();
application.createAccount(newAccount,function(err){
if(err){
done(err);
before(function(done){
newAccount = helpers.fakeAccount();
unsignedToken = nJwt.create({hello:'world'},'not a secret').compact();
helpers.createApplication(function(err,app){
if(err){
done(err);
}else{
application = app;
expiredToken = nJwt.create(
{hello:'world'},
application.dataStore.requestExecutor.options.client.apiKey.secret
).setExpiration(new Date().getTime())
.compact();
application.createAccount(newAccount,function(err){
if(err){
done(err);
AuthenticationResult.prototype.getJwt = function getJwt() {
var secret = this.application.dataStore.requestExecutor
.options.client.apiKey.secret;
var jwt = nJwt.create({
iss: this.application.href,
sub: this.forApiKey ? this.forApiKey.id : this.account.href,
jti: utils.uuid()
}, secret);
jwt.setExpiration(new Date().getTime() + (this.ttl * 1000));
return jwt;
};
claims.cb_uri = options.cb_uri;
}
if (options.ash) {
claims.ash = options.ash;
}
if (options.onk) {
claims.onk = options.onk;
}
if (options.state) {
claims.state = options.state;
}
var accessToken = njwt.create(claims, apiKey.secret);
accessToken.header.kid = apiKey.id;
var parameters = {
accessToken: accessToken.compact()
};
var ssoInitiationEndpoint = serviceProvider.ssoInitiationEndpoint.href;
var initializationUrl = self._buildInitializationUrl(ssoInitiationEndpoint, parameters);
args.callback(null, initializationUrl);
});
};
createToken(user) {
return njwt
.create(
{
iss: conf.domain,
sub: user.id,
name: user.name,
email: user.email,
organizations: user.organizations,
id: user.id,
date: Date.now()
},
secretKey
)
.compact()
}
payload.onk = options.organizationNameKey;
}
if(typeof options.useSubDomain === 'boolean'){
payload.usd = options.useSubDomain;
}
if(Array.isArray(options.require_mfa)){
payload.require_mfa = options.require_mfa;
}
if(Array.isArray(options.challenge)){
payload.challenge = options.challenge;
}
var token = njwt.create(payload,apiKey.secret,'HS256');
var redirectUrl = base + '/sso'+(options.logout?'/logout':'')+'?jwtRequest=' + token;
return redirectUrl;
};