Validates that the data for a jwt token is valid
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',
            )
249600
def ValidateIapJwt(iap_jwt, expected_audience):
  """"""

  try:
    key_id = jwt.get_unverified_header(iap_jwt).get("kid")
    if not key_id:
      raise IAPValidationFailedError("No key ID")
    key = GetIapKey(key_id)
    decoded_jwt = jwt.decode(
        iap_jwt, key, algorithms=["ES256"], audience=expected_audience)
    return (decoded_jwt["sub"], decoded_jwt["email"])
  except (jwt.exceptions.InvalidTokenError,
          requests.exceptions.RequestException) as e:
    raise IAPValidationFailedError(e)
124455
def _validate(claims, validate_claims, expiry_seconds):
    
    if not validate_claims:
        return

    now = time()

    # TODO: implement support for clock skew

    # The exp (expiration time) claim identifies the expiration time on or
    # after which the JWT MUST NOT be accepted for processing. The
    # processing of the exp claim requires that the current date/time MUST
    # be before the expiration date/time listed in the exp claim.
    try:
        expiration_time = claims[CLAIM_EXPIRATION_TIME]
    except KeyError:
        pass
    else:
        _check_expiration_time(now, expiration_time)

    # The iat (issued at) claim identifies the time at which the JWT was
    # issued. This claim can be used to determine the age of the JWT.
    # If expiry_seconds is provided, and the iat claims is present,
    # determine the age of the token and check if it has expired.
    try:
        issued_at = claims[CLAIM_ISSUED_AT]
    except KeyError:
        pass
    else:
        if expiry_seconds is not None:
            _check_expiration_time(now, issued_at + expiry_seconds)

    # The nbf (not before) claim identifies the time before which the JWT
    # MUST NOT be accepted for processing. The processing of the nbf claim
    # requires that the current date/time MUST be after or equal to the
    # not-before date/time listed in the nbf claim.
    try:
        not_before = claims[CLAIM_NOT_BEFORE]
    except KeyError:
        pass
    else:
        _check_not_before(now, not_before)
556974
private function validateToken(JwtToken $token, $isRefresh = false)
    {
        $data = new ValidationData();
        if (isset($this->config['issuer'])) {
            $data->setIssuer($this->config['issuer']);
        }
        if (isset($this->config['audience'])) {
            $data->setAudience($this->config['audience']);
        }
        if ($isRefresh) {
            $data->setExpiration(time() - $this->config['refreshOffsetAllowance']);
        }
        if (!$token->validate($data)) {
            return false;
        }
        return true;
    }
423263
def info(self, token):
        
        verifier = JWT(key_jar=self.key_jar, allowed_sign_algs=[self.alg])
        _payload = verifier.unpack(token)
        if is_expired(_payload['exp']):
            raise ToOld('Token has expired')
        return _payload['sid'], _payload['ttype']
500948
function validateAuthData(authData, config) {
  var appSecretProof = crypto.createHmac('sha256', config.appSecret).update(authData.access_token).digest('hex');
  return graphRequest('me/?access_token=' + authData.access_token + '&appsecret_proof=' + appSecretProof)
    .then((data) => {
      if (data && data.id == authData.id) {
        return;
      }
      throw new Parse.Error(
        Parse.Error.OBJECT_NOT_FOUND,
        'AccountKit auth is invalid for this user.');
    });
}
1156080
function validateToken(bearerToken) {
    var validatedToken = bearerToken;
    if (bearerToken.startsWith('bearer ')) {
        validatedToken = bearerToken.replace('bearer ', '');
    }
    return validatedToken;
}
154090
public Boolean validate(String token, JwtUserDetail userDetails) {
        if (StringUtils.isBlank(token) || userDetails == null) {
            return false;
        }
        String key = jwtProperties.getPrefix() + Md5Utils.digestMD5(token);
        JwtToken jwtToken = cacheService.get(key);
        // 判断是否在黑名单中
        if (jwtToken != null) {
            //销毁状态
            if (JwtToken.Operation.destroy.getValue() == jwtToken.getType()) {
                return false;
            }

            Long refreshTime = jwtToken.getRefreshTime();
            if (refreshTime != null && jwtToken.getType() == JwtToken.Operation.refresh.getValue()) {
                // 刷新token二分钟内可以使用
                return Instant.now().toEpochMilli() - refreshTime < 1000 * 60 * 2;
            }
        }
        final Instant created = jwtBuilder.getCreatedTimeFromToken(token);
        final String loginName = jwtBuilder.getLoginNameFromToken(token);
        LocalDateTime modifyPasswordTime = userDetails.getModifyPasswordTime();
        if (Objects.isNull(modifyPasswordTime)) {
            return Objects.equals(loginName, userDetails.getUsername())
                    && !jwtBuilder.isExpired(token);
        }
        return Objects.equals(loginName, userDetails.getUsername())
                && !jwtBuilder.isExpired(token) && validate(created, modifyPasswordTime);
    }
857768
def valid(cls, data, context=None):
        """"""
        return cls(cls.TagType.VALID, data, context)
532182
async function _verifyToken (jwksClient, token) {
  const decoded = jwt.decode(token, { complete: true })
  const signingKey = await jwksClient.getSigningKeyAsync(decoded.header.kid)
  return jwt.verifyAsync(token, signingKey.publicKey || signingKey.rsaPublicKey)
}
204846
def _verify(
        self,
        request,
        return_payload=False,
        verify=True,
        raise_missing=False,
        request_args=None,
        request_kwargs=None,
        *args,
        **kwargs
    ):
        
        try:
            token = self._get_token(request)
            is_valid = True
            reason = None
        except (
            exceptions.MissingAuthorizationCookie,
            exceptions.MissingAuthorizationQueryArg,
            exceptions.MissingAuthorizationHeader,
        ) as e:
            token = None
            is_valid = False
            reason = list(e.args)
            status = e.status_code if self.config.debug() else 401

            if raise_missing:
                if not self.config.debug():
                    e.status_code = 401
                raise e

        if token:
            try:
                payload = self._decode(token, verify=verify)

                if verify:
                    if self._extra_verifications:
                        self._verify_extras(payload)
                    if self._custom_claims:
                        self._verify_custom_claims(payload)
            except (
                jwt.exceptions.ExpiredSignatureError,
                jwt.exceptions.InvalidIssuerError,
                jwt.exceptions.ImmatureSignatureError,
                jwt.exceptions.InvalidIssuedAtError,
                jwt.exceptions.InvalidAudienceError,
                InvalidVerificationError,
                InvalidCustomClaimError,
            ) as e:
                # Make sure that the reasons all end with '.' for consistency
                reason = [
                    x if x.endswith(".") else "{}.".format(x)
                    for x in list(e.args)
                ]
                payload = None
                status = 401
                is_valid = False
            except jwt.exceptions.DecodeError as e:
                self._reasons = e.args
                # Make sure that the reasons all end with '.' for consistency
                reason = (
                    [
                        x if x.endswith(".") else "{}.".format(x)
                        for x in list(e.args)
                    ]
                    if self.config.debug()
                    else "Auth required."
                )
                logger.debug(e.args)
                is_valid = False
                payload = None
                status = 400 if self.config.debug() else 401
        else:
            payload = None

        if return_payload:
            return payload

        status = 200 if is_valid else status

        return is_valid, status, reason
1347214
def validate(self):
        

        try:
            resp = self.request().get(self.validate_url, verify=self.verifySSL).json()
        except TokenExpiredError:
            return False
        except AttributeError:
            return False

        if 'error' in resp:
            return False
        return True
641045
function doTokenValidation(token,publicKey,appId) {
	  var parts = token.split('.');
	  if (parts.length < 3) {
            ibmlogger.getLogger().debug("The token decode failure details:", token);
            return Q.reject(RejectionMessage("The token is malformed.", token,RejectionMessage.INVALID_TOKEN_ERROR));
	  }
		    
	  if (parts[2].trim() === '' && publicKey) {
		  return Q.reject(RejectionMessage("The token missing the signature.", token,RejectionMessage.INVALID_TOKEN_ERROR));
	  }

	  var valid;
	  if (publicKey) {
		  try {
		    valid = jws.verify(token, publicKey);
			if (!valid) {
				return Q.reject(RejectionMessage("The token was verified failed with the public key.", token,RejectionMessage.INVALID_TOKEN_ERROR));
			}
		  }
		  catch (e) {
			return Q.reject(RejectionMessage("An error occurred when verifying the token"+e.message, token, RejectionMessage.INVALID_TOKEN_ERROR));
		  }
	  }
	  
	  var decodedToken = jws.decode(token,{json:true});
	  if (!decodedToken) {
		  return Q.reject(RejectionMessage("The token was decoded failed", token, RejectionMessage.INVALID_TOKEN_ERROR));
	  }
	  
	  var payload = decodedToken.payload;
	  
	  if (payload.exp) {
		  if (Math.round(Date.now()) / 1000 >= payload.exp) {
			  return Q.reject(RejectionMessage("The token has been expired.", token, RejectionMessage.INVALID_TOKEN_ERROR));
		  }
	  }
	  
	  if (payload.aud) {
		  if (payload.aud != appId) {
			  return Q.reject(RejectionMessage("The aud in token is inconsistent with the given application id."+payload.aud+","+appId, token, RejectionMessage.INVALID_TOKEN_ERROR));
		  }
	  }
	  /*
	  if (options.audience) {
		  if (payload.aud !== options.audience) {
			  return Q.reject(RejectionMessage("The audience is different from the expected aud:"+options.audience, token, RejectionMessage.INVALID_TOKEN_ERROR));
		  }
	  }

	  if (options.issuer) {
		    if (payload.iss !== options.issuer) {
		    	return Q.reject(RejectionMessage("The issuer is different from the expected iss:"+options.issuer, token, RejectionMessage.INVALID_TOKEN_ERROR));
		    }
	  }
	  */
	  return Q.resolve(payload);
}
257002
def validate(data):
    
    text = data.get('text')
    if not isinstance(text, _string_types) or len(text) == 0:
        raise ValueError('text field is required and should not be empty')

    if 'markdown' in data and not type(data['markdown']) is bool:
        raise ValueError('markdown field should be bool')

    if 'attachments' in data:
        if not isinstance(data['attachments'], (list, tuple)):
            raise ValueError('attachments field should be list or tuple')

        for attachment in data['attachments']:
            if 'text' not in attachment and 'title' not in attachment:
                raise ValueError('text or title is required in attachment')

    return True
574306
@GET
    @Path("/validate/{token}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response validateAccount(@PathParam("token") String token) {
        try{
            if (authServerLogic.validateAccount(token)) {
                return Response.ok().build();
            } else {
                return Response.status(Status.NOT_FOUND).build();
            }
        }catch (ServerDAO.DAOException e) {
            return fromDAOExpection(e);
        }
    }
13218
def validate_token(self, token):
    '''
    '''
    from expfactory.database.models import Participant
    p = Participant.query.filter(Participant.token == token).first()
    if p is not None:
        if p.token.endswith(('finished','revoked')):
            p = None
        else:
            p = p.id
    return p
96575
function verifySignedJwtWithCerts($jwt, $certs, $required_audience) {
    $segments = explode(".", $jwt);
    if (count($segments) != 3) {
      throw new AuthException("Wrong number of segments in token: $jwt");
    }
    $signed = $segments[0] . "." . $segments[1];
    $signature = Utils::urlSafeB64Decode($segments[2]);

    // Parse envelope.
    $envelope = json_decode(Utils::urlSafeB64Decode($segments[0]), true);
    if (!$envelope) {
      throw new AuthException("Can't parse token envelope: " . $segments[0]);
    }

    // Parse token
    $json_body = Utils::urlSafeB64Decode($segments[1]);
    $payload = json_decode($json_body, true);
    if (!$payload) {
      throw new AuthException("Can't parse token payload: " . $segments[1]);
    }

    // Check signature
    $verified = false;
    foreach ($certs as $keyName => $pem) {
      $public_key = new PemVerifier($pem);
      if ($public_key->verify($signed, $signature)) {
        $verified = true;
        break;
      }
    }

    if (!$verified) {
      throw new AuthException("Invalid token signature: $jwt");
    }

    // Check issued-at timestamp
    $iat = 0;
    if (array_key_exists("iat", $payload)) {
      $iat = $payload["iat"];
    }
    if (!$iat) {
      throw new AuthException("No issue time in token: $json_body");
    }
    $earliest = $iat - self::CLOCK_SKEW_SECS;

    // Check expiration timestamp
    $now = time();
    $exp = 0;
    if (array_key_exists("exp", $payload)) {
      $exp = $payload["exp"];
    }
    if (!$exp) {
      throw new AuthException("No expiration time in token: $json_body");
    }
    if ($exp >= $now + self::MAX_TOKEN_LIFETIME_SECS) {
      throw new AuthException(
          "Expiration time too far in future: $json_body");
    }

    $latest = $exp + self::CLOCK_SKEW_SECS;
    if ($now < $earliest) {
      throw new AuthException(
          "Token used too early, $now < $earliest: $json_body");
    }
    if ($now > $latest) {
      throw new AuthException(
          "Token used too late, $now > $latest: $json_body");
    }

    // TODO(beaton): check issuer field?

    // Check audience
    $aud = $payload["aud"];
    if ($aud != $required_audience) {
      throw new AuthException("Wrong recipient, $aud != $required_audience: $json_body");
    }

    // All good.
    return new LoginTicket($envelope, $payload);
  }