示例#1
0
      authenticationContext.acquireTokenWithAuthorizationCode(req.query.code, redirectUri, resource, clientId, clientSecret, function(err, response) {
          if (!err) {

            // build the claims
            var claims = {
                iss: "http://testauth.plasne.com",
                sub: response.userId,
                scope: "[admin]"
            };

            // build the JWT
            var jwt = nJwt.create(claims, jwtKey);
            jwt.setExpiration(new Date().getTime() + (4 * 60 * 60 * 1000)); // 4 hours

            // return the JWT
            res.cookie("accessToken", jwt.compact(), {
                maxAge: 4 * 60 * 60 * 1000 // 4 hours
            });
            res.redirect("/admin.htm");

          } else {
              console.log("token: an authorization token could not be obtained - " + err);
              res.sendError("auth");
          }
      });
示例#2
0
    getGroupMembershipForUser(token).then(function(groups) {

        // build a list of group names
        const membership = [];
        groups.forEach(function(group) {
            if (group.displayName.startsWith("testauth_")) {
                membership.push(group.displayName.replace("testauth_", ""));
            }
        });

        // define rights
        const rights = [];
        if (membership.indexOf("admins") > -1) {
            rights.push("can admin");
            rights.push("can edit");
            rights.push("can view");
        } else if (membership.indexOf("users") > -1) {
            rights.push("can view");
        }

        // build the claims
        const claims = {
            iss: "http://testauth.plasne.com",
            sub: userId,
            scope: membership,
            rights: rights
        };

        // build the JWT
        const jwt = nJwt.create(claims, jwtKey);
        jwt.setExpiration(new Date().getTime() + (4 * 60 * 60 * 1000)); // 4 hours
        deferred.resolve(jwt.compact());

    }, function(msg) {
  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);
          }else{
            new stormpath.OAuthPasswordGrantRequestAuthenticator(application)
              .authenticate({
                username: newAccount.email,
                password: newAccount.password
              },function(err,accessTokenResponse){
                passwordGrantResponse = accessTokenResponse;
              });

            helpers.createApplication(function(err,app2){
              if(err){
                done(err);
              }else{
                application2 = app2;
                /*
                  We are setting the token ttl to 10 seconds, beacuse
                  we want to test expired tokens in this test
                 */
                application2.getOAuthPolicy(function(err,policy){
                  if(err){
                    done(err);
                  }else{
                    policy.accessTokenTtl = 'PT10S';
                    policy.save(function(err){
                      if(err){
                        done(err);
                      }else{
                        application2.createAccount(newAccount,done);
                      }
                    });
                  }
                });
              }
            });
          }
        });
      }

    });
  });
AuthenticationResult.prototype.getJwt = function getJwt() {
  var self = this;
  return nJwt.create({
    iss: self.application.href,
    sub: self.forApiKey ? self.forApiKey.id : self.account.href,
    jti: utils.uuid()
  },self.application.dataStore.requestExecutor.options.client.apiKey.secret)
  .setExpiration(new Date().getTime() + (3600*1000));
};
  }).spread((authenticated, user) => {
    if (!authenticated) {
      return [ false, null ];
    }

    // Authenticated, create the token
    var token = nJwt.create({ sub: user.id }, request.server.settings.app.security.key);

    return request.server.app.cache.session.setAsync(token.body.jti, token.body, 0).return([ authenticated, token ]);
  }).spread((authenticated, token) => {
示例#6
0
文件: jwt.js 项目: icapps/Celeste
 module.createJWTToken = function(userId) {
     var payload = {
         sub: userId,
         iat: moment().unix(),
         exp: moment().add(1, 'days').unix(),
         iss: process.env.BASE_URL,
         aud: process.env.BASE_URL
     };
     var token = nJwt.create(payload, tokenSecret);
     return token.compact();
 };
示例#7
0
文件: routes.js 项目: skoocda/spreza
 user.comparePassword(req.body.password, function(err, isMatch){
     // If an error occured with comparing passwords
     if (err){
         return res.status(500).send(
             utils.errorResponse('ER_SERVER', err)
         );
     }
     // If the user is not verified
     if (!user.isVerified){
         return res.status(400).send(
             utils.errorResponse('ER_USER_NOT_VERIFIED')
         );
     }
     // If the password is incorrect
     if (!isMatch){
         return res.status(400).send(
             utils.errorResponse('ER_WRONG_PASSWORD')
         );
     }
     // If the user exists and password is correct, create TMP folder
     rmdir(utils.getUserTempFolderPath(user._id), function(err){
         // If an error occured with deleting the TMP folder
         if (err){
             return res.status(500).send(
                 utils.errorResponse('ER_SERVER', err)
             );
         }
         mkdir(utils.getUserTempFolderPath(user._id), function(err){
             // If an error occured with creating the TMP folder
             if (err){
                 return res.status(500).send(
                     utils.errorResponse('ER_SERVER', err)
                 );
             }
         });
     });
     // Prepare the claims for the user's session
     var claims = {
         sub: user._id,
         iss: config.HOST,
         permissions: 'Default'
     };
     // Generate the JSON web token and set to expire in 10 hours
     var token = nJwt.create(claims, config.KEY.SESSION);
     token.setExpiration(new Date().getTime() + 36000000);
     var compactToken = token.compact();
     // Create a new cookie that stores the compact token
     new cookies(req, res).set(
         'access_token', compactToken, config.COOKIE_FLAGS
     );
     return res.sendStatus(200);
 });
  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);
          }else{

            helpers.createApplication(function(err,app2){
              if(err){
                done(err);
              }else{
                application2 = app2;
                /*
                  We are setting the token ttl to 2 seconds, beacuse
                  we want to test expired tokens in this test
                 */
                application2.getOAuthPolicy(function(err,policy){
                  if(err){
                    done(err);
                  }else{
                    policy.accessTokenTtl = 'PT2S';
                    policy.save(function(err){
                      if(err){
                        done(err);
                      }else{
                        application2.createAccount(newAccount,done);
                      }
                    });
                  }
                });
              }
            });
          }
        });
      }

    });
  });
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;
};
示例#10
0
    verifyToken(token).then(function(verified) {
        
        // native apps cannot do admin consent, so we cannot reach back into the user's AAD, but we can generate a JWT without any special
        //   authorization and assume we do that in our application
        const claims = {
            iss: "http://testauth.plasne.com",
            sub: verified.body.upn
        };

        // build the JWT
        const jwt = nJwt.create(claims, jwtKey);
        jwt.setExpiration(new Date().getTime() + (4 * 60 * 60 * 1000)); // 4 hours
        res.status(200).send({ "accessToken": jwt.compact() });

    }, function(msg) {
示例#11
0
      client.getGroupMembershipForUser(credentials.username, function(err, groups) {
        if (err) {
            res.status(500).send(JSON.stringify(err));
        }
        if (groups) {
            
            // build a list of group names
            var membership = [];
            groups.forEach(function(group) {
                if (group.cn.startsWith("testauth_")) {
                    membership.push(group.cn.replace("testauth_", ""));
                }
            });

            // define rights
            var rights = [];
            if (membership.indexOf("admins") > -1) {
                rights.push("can admin");
                rights.push("can edit");
                rights.push("can view");
            } else if (membership.indexOf("users") > -1) {
                rights.push("can view");
            }
 
            // build the claims
            var claims = {
                iss: "http://testauth.plasne.com",
                sub: credentials.username,
                scope: membership,
                rights: rights
            };

            // build the JWT
            var jwt = nJwt.create(claims, jwtKey);
            jwt.setExpiration(new Date().getTime() + (4 * 60 * 60 * 1000)); // 4 hours
            res.cookie("accessToken", jwt.compact(), {
                maxAge: 4 * 60 * 60 * 1000
            });

            // return to the client
            res.status(200).end();

        }
      });
示例#12
0
        promise.each([create, list], function(result) { }).then(function(result) {
            var entry = result[1];

            // build the claims
            var claims = {
                iss: "http://testauth.plasne.com",
                sub: entry.RowKey._,
                scope: entry.container._
            };

            // build the JWT
            var jwt = nJwt.create(claims, jwtKey);
            jwt.setExpiration(new Date().getTime() + (24 * 60 * 60 * 1000)); // 24 hours

            // return the JWT
            res.cookie("accessToken", jwt.compact(), {
                maxAge: 24 * 60 * 60 * 1000 // 24 hours
            });
            res.status(200).end();

        }, function(error) {
示例#13
0
        encode: function() {
            this.changedFromEncode = true;

            if(this.validateValues() == false) {
                this.jwt.token = '';
                this.jsonError = true;
                this.jsonErrorMessage = "Some Values are invalid.";
            }
            try {
                var token = nJwt.create(JSON.parse(this.jwt.payload),this.jwt.key);
                this.jwt.token = token.compact();
                this.jsonError = false;
                this.jsonErrorMessage = "";
                this.generateCode();
                this.verifyKey();
            } catch(err) {
                this.jwt.token = '';
                this.jsonError = true;
                this.jsonErrorMessage = err.toString();
            }
        },
示例#14
0
  this._getServiceProvider(function (err, serviceProvider) {
    if (err) {
      return callback(err);
    }

    var claims = {
      jti: uuid(),
      iss: self.application.href,
      iat: new Date().getTime() / 1000
    };

    if (options.cb_uri) {
      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);

    callback(null, initializationUrl);
  });
示例#15
0
var jwtTool = require('njwt'),
    fs = require('fs');

var claimsJSON = fs.readFileSync(__dirname + '/../config/claims.json', 'utf8');
var secretJSON = fs.readFileSync(__dirname + '/../config/secret.json', 'utf8');
var secret = JSON.parse(secretJSON).secretKey;
var claims = JSON.parse(claimsJSON);

var jwt = jwtTool.create(claims, secret);

console.log(claimsJSON);
console.log("key: " + secret);
console.log("jwt:");
console.log(jwt);
console.log();
console.log(jwt.compact());
示例#16
0
// #TODO find a better way to define this
Date.prototype.toMysqlFormat = function () {
  return this.getUTCFullYear() +
    "-" + twoDigits(1 + this.getUTCMonth()) +
    "-" + twoDigits(this.getUTCDate()) +
    " " + twoDigits(this.getUTCHours()) +
    ":" + twoDigits(this.getUTCMinutes()) +
    ":" + twoDigits(this.getUTCSeconds());
};

exports.Utils = {
  generateAuthToken(id, secret) {
    let claims = {
      sub: id,
      iss: 'api.beersdepot.com',
      permissions: 'user'
    };

    let jwt = nJwt.create(claims, secret);
    // Set 1 week expiration period
    jwt.setExpiration(new Date().getTime() + (config.tokenExpiration.value));
    return jwt.compact();
  },
  verifyAuthToken(token, secret, proceed) {
    nJwt.verify(token, secret, (err, token) => {
      proceed(err, token);
    });
  }
}
示例#17
0
 generateJwt: function() {
     var jwt = nJwt.create(JSON.parse("{\"sub\": \"1234567890\", \"name\":\"John Doe\", \"admin\":true}"), this.jwt.key);
     this.jwt.token = jwt.compact();
     this.decode();
 },
示例#18
0
var uuid = require('node-uuid')
var nJwt  = require('njwt')

var secretKey = uuid.v4()

var claims = {
	sub: (new Date()).getDate(),
	iss: 'http://localhost:3000',
	permissions: ['users-index', 'user-create']
}

var jwt = nJwt.create(claims, secretKey)

console.log(JSON.stringify(jwt))
console.log(jwt.compact(), secretKey)