How to use njwt - 10 common examples

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 / paywall.js View on Github external
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', () => {
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 / controllers / revoke-token.js View on Github external
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);
    });
  }
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 / stormpath-sdk-node / test / it / api_auth_it.js View on Github external
},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();
        });
      });
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-express / test / authenticateBearerAuthorizationHeader.js View on Github external
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(){
github stormpath / stormpath-sdk-express / test / authenticateBearerAuthorizationHeader.js View on Github external
it('should error',function(done){
      request(app)
        .post(protectedEndpoint)
        .set('Authorization', 'Bearer ' + expiredToken)
        .send(postData)
        .expect(401,{errorMessage:jwtErrors.EXPIRED},done);
    });
  });
github stormpath / stormpath-sdk-express / test / authenticateBearerAuthorizationHeader.js View on Github external
it('should error',function(done){
      request(app)
        .post(protectedEndpoint)
        .set('Authorization', 'Bearer ' + fakeToken)
        .send(postData)
        .expect(401,{errorMessage:jwtErrors.SIGNATURE_MISMTACH},done);
    });
  });
github stormpath / stormpath-sdk-node / test / it / saml_idp_url_builder_it.js View on Github external
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();
        });
      });