Check the JWT token for collab server
169503
function checkCollabServerToken(authorization) {
		if (authorization.substr(0, 7) !== "Bearer ") {
			return false;
		}
		try {
			var decoded = jwt.verify(authorization.substr(7), options.configParams.get("orion.jwt.secret"));
			return true;
		} catch (ex) {
			return false;
		}
	}
967129
function(token, cb){
      try{
        // decode the token
        var _token = waterlock.jwt.decode(token, waterlock.config.jsonWebTokens.secret);

        // set the time of the request
        var _reqTime = Date.now();

        // If token is expired
        if(_token.exp <= _reqTime){
          waterlock.logger.debug('access token rejected, reason: EXPIRED');
          return cb('Your token is expired.');
        }

        // If token is early
        if(_reqTime <= _token.nbf){
          waterlock.logger.debug('access token rejected, reason: TOKEN EARLY');
          return cb('This token is early.');
        }

        // If audience doesn't match
        if(waterlock.config.jsonWebTokens.audience !== _token.aud){
          waterlock.logger.debug('access token rejected, reason: AUDIENCE');
          return cb('This token cannot be accepted for this domain.');
        }

        this.findUserFromToken(_token, cb);

      } catch(err){
        cb(err);
      }
    }
1129084
def jwt_proccessor():
    """"""
    def jwt():
        """Context processor function to generate jwt."""
        token = current_accounts.jwt_creation_factory()
        return Markup(
            render_template(
                current_app.config['ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE'],
                token=token
            )
        )

    def jwt_token():
        """Context processor function to generate jwt."""
        return current_accounts.jwt_creation_factory()

    return {
        'jwt': jwt,
        'jwt_token': jwt_token,
    }
128332
public CheckTokenResponse checkToken(TokenRequest tokenInfo) throws ApiException {
        ApiResponse<CheckTokenResponse> resp = checkTokenWithHttpInfo(tokenInfo);
        return resp.getData();
    }
189450
function tokenNotExpired(tokenName, jwt) {
    if (tokenName === void 0) { tokenName = AuthConfigConsts.DEFAULT_TOKEN_NAME; }
    var token = jwt || localStorage.getItem(tokenName) || sessionStorage.getItem(tokenName);
    var jwtHelper = new JwtHelper();
    return token != null && !jwtHelper.isTokenExpired(token);
}
799934
public String getJwtTokenUsingBuilder(String testName, LibertyServer server, String builderId, List<NameValuePair> extraClaims) throws Exception {

        String jwtBuilderUrl = SecurityFatHttpUtils.getServerUrlBase(server) + "/jwtbuilder/build";

        List<NameValuePair> requestParams = setRequestParms(builderId, extraClaims);

        WebClient webClient = new WebClient();
        Page response = invokeUrlWithParameters(testName, webClient, jwtBuilderUrl, requestParams);
        Log.info(thisClass, testName, "JWT builder app response: " + WebResponseUtils.getResponseText(response));

        Cookie jwtCookie = webClient.getCookieManager().getCookie("JWT");
        Log.info(thisClass, testName, "Built JWT cookie: " + jwtCookie);
        Log.info(thisClass, testName, "Cookie value: " + jwtCookie.getValue());
        return jwtCookie.getValue();

    }
638934
def verifyJWT(self, token):
        
        logging.debug("verify token: {0}".format(token))
        #1. 拆分解析
        if isinstance(token, (str, unicode)):
            if token.count(".") == 2:
                token = self.analysisJWT(token)
            else:
                raise InvalidTokenError("invalid token")
        else:
            raise TypeError("token is in string or Unicode format")

        #2. 验证header
        if self._header == token["header"]:
            payload = token["payload"]
        else:
            raise InvalidTokenError("header missmatch")

        #3. 验证payload
        for i in self._payloadkey:
            if i in ("exp", "iat"): continue
            #logging.debug("verify payload key: {0}: {1}".format(i, payload.get(i) == self._payload.get(i)))
            if payload.get(i) != self._payload.get(i):
                raise InvalidTokenError("payload contains standard declaration keys")
        if self.get_current_timestamp() > payload["exp"]:
            raise TokenExpiredError("token expired")

        #4. 验证签名
        #头部编码
        first_part  = base64.urlsafe_b64encode(json.dumps(token["header"], sort_keys=True, separators=(',', ':')))
        #载荷消息体编码
        second_part = base64.urlsafe_b64encode(json.dumps(token["payload"], sort_keys=True, separators=(',', ':')))
        #签名以上两部分: 把header、playload的base64url编码加密后再次base64编码.
        third_part  = self.signatureJWT("{0}.{1}".format(first_part, second_part))
        #此处......
        if token["signature"] == third_part:
            logging.info("verify token pass")
            return True
        else:
            raise SignatureBadError("invalid signature")
779797
def authenticate_token(self, load):
        '''
        
        '''
        token = self.get_tok(load['token'])

        # Bail if the token is empty or if the eauth type specified is not allowed
        if not token or token['eauth'] not in self.opts['external_auth']:
            log.warning('Authentication failure of type "token" occurred.')
            return False

        return token
1032534
def payload(self):
        
        _msg = as_unicode(self.part[1])

        # If not JSON web token assume JSON
        if "cty" in self.headers and self.headers["cty"].lower() != "jwt":
            pass
        else:
            try:
                _msg = json.loads(_msg)
            except ValueError:
                pass

        return _msg
875336
def is_expired(self, token, when=0):
        
        verifier = JWT(key_jar=self.key_jar, allowed_sign_algs=[self.alg])
        _payload = verifier.unpack(token)
        return is_expired(_payload['exp'], when)
330990
def _validate_jwt_data(self, data, access_type):
        
        MissingClaimError.require_condition(
            'jti' in data,
            'Token is missing jti claim',
        )
        BlacklistedError.require_condition(
            not self.is_blacklisted(data['jti']),
            'Token has a blacklisted jti',
        )
        MissingClaimError.require_condition(
            'id' in data,
            'Token is missing id field',
        )
        MissingClaimError.require_condition(
            'exp' in data,
            'Token is missing exp claim',
        )
        MissingClaimError.require_condition(
            'rf_exp' in data,
            'Token is missing rf_exp claim',
        )
        moment = pendulum.now('UTC').int_timestamp
        if access_type == AccessType.access:
            ExpiredAccessError.require_condition(
                moment <= data['exp'],
                'access permission has expired',
            )
        elif access_type == AccessType.refresh:
            EarlyRefreshError.require_condition(
                moment > data['exp'],
                'access permission for token has not expired. may not refresh',
            )
            ExpiredRefreshError.require_condition(
                moment <= data['rf_exp'],
                'refresh permission for token has expired',
            )
1066081
def is_authenticated(self):
        
        token = self.con.token_backend.token
        if not token:
            token = self.con.token_backend.get_token()

        return token is not None and not token.is_expired
258671
function ensureValidJWTCookie(request) {
    const originalRequest = request;
    const isAuthUrl = authenticatedAPIClient.isAuthUrl(originalRequest.url);
    const accessToken = authenticatedAPIClient.getDecodedAccessToken();
    const tokenExpired = authenticatedAPIClient.isAccessTokenExpired(accessToken);
    if (isAuthUrl || !tokenExpired) {
      return request;
    }

    if (!queueRequests) {
      queueRequests = true;
      authenticatedAPIClient.refreshAccessToken()
        .then(() => {
          queueRequests = false;
          PubSub.publishSync(ACCESS_TOKEN_REFRESH, { success: true });
        })
        .catch((error) => {
          // If no callback is supplied frontend-auth will (ultimately) redirect the user to login.
          // The user is redirected to logout to ensure authentication clean-up, which in turn
          // redirects to login.
          if (authenticatedAPIClient.handleRefreshAccessTokenFailure) {
            authenticatedAPIClient.handleRefreshAccessTokenFailure(error);
          } else {
            authenticatedAPIClient.logout();
          }
          PubSub.publishSync(ACCESS_TOKEN_REFRESH, { success: false });
        });
    }

    return new Promise((resolve, reject) => {
      logInfo(`Queuing API request ${originalRequest.url} while access token is refreshed`);
      PubSub.subscribeOnce(ACCESS_TOKEN_REFRESH, (msg, { success }) => {
        if (success) {
          logInfo(`Resolving queued API request ${originalRequest.url}`);
          resolve(originalRequest);
        } else {
          reject(originalRequest);
        }
      });
    });
  }
1224601
def check_token(data: dict, token: str) -> bool:
    
    param_hash = data.get('hash', '') or ''
    return param_hash == generate_hash(data, token)
270145
def sign_jwt(data, secret_key, expires_in, salt=None, **kw):
    
    s = itsdangerous.TimedJSONWebSignatureSerializer(secret_key=secret_key,
                                                     expires_in=expires_in,
                                                     salt=salt,
                                                      **kw)
    return s.dumps(data)
481711
def VerifyGitkitToken(self, jwt):
    
    certs = self.rpc_helper.GetPublicCert()
    crypt.MAX_TOKEN_LIFETIME_SECS = 30 * 86400  # 30 days
    parsed = None
    for aud in filter(lambda x: x is not None, [self.project_id, self.client_id]):
      try:
        parsed = crypt.verify_signed_jwt_with_certs(jwt, certs, aud)
      except crypt.AppIdentityError as e:
        if "Wrong recipient" not in e.message:
          return None
      if parsed:
        return GitkitUser.FromToken(parsed)
    return None
680230
def _verify_token(self):
        
        res = self._session.get(self._token_verification_url)
        if not res.ok:
            raise exceptions.BadToken(consts.LOG_MSG_BAD_TOKEN)
        return True