How to use the njwt.create function in njwt

To help you get started, we’ve selected a few njwt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aws-samples / aws-serverless-subscription-service-node / login.js View on Github external
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);
                            }
github stormpath / express-stormpath / lib / helpers / exchange-stormpath-token.js View on Github external
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]);
    }
github stormpath / express-stormpath / test / middlewares / test-default-organization-resolver.js View on Github external
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);
github stormpath / stormpath-sdk-node / test / it / jwt_authenticator_it.js View on Github external
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);
github stormpath / stormpath-sdk-node / test / it / oauth_authenticator_it.js View on Github external
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);
github stormpath / stormpath-sdk-node / lib / resource / AuthenticationResult.js View on Github external
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;
};
github stormpath / stormpath-sdk-node / lib / saml / SamlIdpUrlBuilder.js View on Github external
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);
  });
};
github misterfresh / react-without-webpack / server / api / models / user.js View on Github external
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()
  }
github stormpath / stormpath-sdk-node / lib / resource / Application.js View on Github external
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;
};