https://developer.zendesk.com/rest_api/docs/core/channel_framework#validate-token
432606
def any_channel_validate_token_create(self, data, **kwargs):
        ""
        api_path = "/api/v2/any_channel/validate_token"
        return self.call(api_path, method="POST", data=data, **kwargs)
1027388
function verifyClientToken (req, res, next) {
  var header = req.headers['authorization']

  // missing header
  if (!header) {
    return next(new UnauthorizedError({
      realm: 'client',
      error: 'unauthorized_client',
      error_description: 'Missing authorization header',
      statusCode: 403
    }))

  // header found
  } else {
    var jwt = header.replace('Bearer ', '')
    var token = ClientToken.decode(jwt, settings.keys.sig.pub)

    // failed to decode
    if (!token || token instanceof Error) {
      next(new UnauthorizedError({
        realm: 'client',
        error: 'unauthorized_client',
        error_description: 'Invalid access token',
        statusCode: 403
      }))

    // decoded successfully
    } else {
      // validate token
      req.token = token
      next()
    }
  }
}
88666
private function validateRequest(ServerRequestInterface $request, array &$tokens)
    {
        $data = $request->getParsedBody();

        if (!isset($data[$this->formIndex]) || !isset($data[$this->formToken])) {
            return false;
        }

        $index = $data[$this->formIndex];
        $token = $data[$this->formToken];

        if (!isset($tokens[$index])) {
            return false;
        }

        $stored = $tokens[$index];
        unset($tokens[$index]);

        $lockTo = $request->getUri()->getPath();

        if (!Utils\Helpers::hashEquals($lockTo, $stored['lockTo'])) {
            return false;
        }

        $expected = self::encode(hash_hmac('sha256', ClientIp::getIp($request), base64_decode($stored['token']), true));

        return Utils\Helpers::hashEquals($token, $expected);
    }
569581
function validateAskPermission (token) {
  const header = jwt.decode(token)

  return validateToken(token) && header[ASK_CLAIM_KEY]
}
28479
public String checkToken (BureauCredentials creds)
    {
        Bureau bureau = _bureaus.get(creds.clientId);
        if (bureau == null) {
            return "Bureau " + creds.clientId + " not found";
        }
        if (bureau.clientObj != null) {
            return "Bureau " + creds.clientId + " already logged in";
        }
        if (!creds.areValid(bureau.token)) {
            return "Bureau " + creds.clientId + " does not match credentials token";
        }
        return null;
    }
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);
  }
114381
public boolean validateAccount(String token) throws DAOException {
            Query q = new QueryBuilder().select().from(Credentials.class).where("validation", OPERAND.EQ, token).build();

            TransientObject to = ObjectUtils.get1stOrNull(dao.query(q));
            if (to != null) {
                ServerCredentials creds = new ServerCredentials(to);
                creds.setValidation("1");
                dao.save(creds);
                return true;
            } else {
                return false;
            }

    }
1079199
function verify(token, sign, options) {
  return function (done) {
    _jsonwebtoken2['default'].verifySync(token, sign, options, done);
  };
}
984663
private static boolean checkTokenValid(final char[] token) {
        if (token == null || token.length == 0) {
            return true;
        }
        for (int i = 0; i < token.length; i++) {
            if (token[i] == '\n') {
                return false;
            }

        }
        return true;
    }
483006
def _validate_token(self):
        
        '''  '''
        
        title = '%s._validate_token' % self.__class__.__name__
    
    # construct access token url
        import requests
        url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % self.access_token
    
    # retrieve access token details
        try:
            token_details = requests.get(url).json()
        except:
            raise DriveConnectionError(title)
        if 'error' in token_details.keys():
            raise ValueError('access_token for google drive account is %s' % token_details['error_description'])
    
    # determine collection space
    # https://developers.google.com/drive/v3/web/about-organization
        if 'scope' in token_details.keys():
            service_scope = token_details['scope']
            if service_scope.find('drive.appfolder') > -1:
                self.drive_space = 'appDataFolder'
                if not self.collection_name:
                    self.collection_name = 'App Data Folder'
            elif service_scope.find('drive.photos.readonly') > -1:
                self.drive_space = 'photos'
                if not self.collection_name:
                    self.collection_name = 'Photos'
    
    # determine permissions
    # https://developers.google.com/drive/v3/web/about-auth
            if service_scope.find('readonly') > -1:
                self.permissions_write = False
            if service_scope.find('readonly.metadata') > -1:
                self.permissions_content = False
          
    # TODO refresh token
        if 'expires_in' in token_details.keys():
            from time import time
            expiration_date = time() + token_details['expires_in']
        if 'issued_to' in token_details.keys():
            client_id = token_details['issued_to']
    
        return token_details
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',
            )
211819
def validate_token_age(callback_token):
    
    try:
        token = CallbackToken.objects.get(key=callback_token, is_active=True)
        seconds = (timezone.now() - token.created_at).total_seconds()
        token_expiry_time = api_settings.PASSWORDLESS_TOKEN_EXPIRE_TIME

        if seconds <= token_expiry_time:
            return True
        else:
            # Invalidate our token.
            token.is_active = False
            token.save()
            return False

    except CallbackToken.DoesNotExist:
        # No valid token.
        return False
464016
def _validate_auth(self, path, obj, _):
        
        errs = []

        if obj.type == 'apiKey':
            if not obj.passAs:
                errs.append('need "passAs" for apiKey')
            if not obj.keyname:
                errs.append('need "keyname" for apiKey')

        elif obj.type == 'oauth2':
            if not obj.grantTypes:
                errs.append('need "grantTypes" for oauth2')

        return path, obj.__class__.__name__, errs
92829
def validate_token_parameters(params):
    """"""
    if 'error' in params:
        raise_from_error(params.get('error'), params)

    if not 'access_token' in params:
        raise MissingTokenError(description="Missing access token parameter.")

    if not 'token_type' in params:
        if os.environ.get('OAUTHLIB_STRICT_TOKEN_TYPE'):
            raise MissingTokenTypeError()

    # If the issued access token scope is different from the one requested by
    # the client, the authorization server MUST include the "scope" response
    # parameter to inform the client of the actual scope granted.
    # https://tools.ietf.org/html/rfc6749#section-3.3
    if params.scope_changed:
        message = 'Scope has changed from "{old}" to "{new}".'.format(
            old=params.old_scope, new=params.scope,
        )
        scope_changed.send(message=message, old=params.old_scopes, new=params.scopes)
        if not os.environ.get('OAUTHLIB_RELAX_TOKEN_SCOPE', None):
            w = Warning(message)
            w.token = params
            w.old_scope = params.old_scopes
            w.new_scope = params.scopes
            raise w
225029
function _checkIsHttpToken(val) {
	if (typeof val !== 'string' || val.length === 0) {
		return false;
	}
	if (!_isValidTokenChar(val.charCodeAt(0))) {
		return false;
	}
	const len = val.length;
	if (len > 1) {
		if (!_isValidTokenChar(val.charCodeAt(1))) {
			return false;
		}
		if (len > 2) {
			if (!_isValidTokenChar(val.charCodeAt(2))) {
				return false;
			}
			if (len > 3) {
				if (!_isValidTokenChar(val.charCodeAt(3))) {
					return false;
				}
				for (var i = 4; i < len; i++) {
					if (!_isValidTokenChar(val.charCodeAt(i))) {
						return false;
					}
				}
			}
		}
	}
	return true;
}
213550
def validate_user(user,
                  device,
                  token):
    '''
    
    '''
    res = {
            'message': 'User key is invalid',
            'result': False
           }

    parameters = dict()
    parameters['user'] = user
    parameters['token'] = token
    if device:
        parameters['device'] = device

    response = query(function='validate_user',
                     method='POST',
                     header_dict={'Content-Type': 'application/x-www-form-urlencoded'},
                     data=_urlencode(parameters))

    if response['res']:
        if 'message' in response:
            _message = response.get('message', '')
            if 'status' in _message:
                if _message.get('dict', {}).get('status', None) == 1:
                    res['result'] = True
                    res['message'] = 'User key is valid.'
                else:
                    res['result'] = False
                    res['message'] = ''.join(_message.get('dict', {}).get('errors'))
    return res
844376
def validate_token_request(self, request):
        
        # REQUIRED. Value MUST be set to "authorization_code".
        if request.grant_type not in ('authorization_code', 'openid'):
            raise errors.UnsupportedGrantTypeError(request=request)

        for validator in self.custom_validators.pre_token:
            validator(request)

        if request.code is None:
            raise errors.InvalidRequestError(
                description='Missing code parameter.', request=request)

        for param in ('client_id', 'grant_type', 'redirect_uri'):
            if param in request.duplicate_params:
                raise errors.InvalidRequestError(description='Duplicate %s parameter.' % param,
                                                 request=request)

        if self.request_validator.client_authentication_required(request):
            # If the client type is confidential or the client was issued client
            # credentials (or assigned other authentication requirements), the
            # client MUST authenticate with the authorization server as described
            # in Section 3.2.1.
            # https://tools.ietf.org/html/rfc6749#section-3.2.1
            if not self.request_validator.authenticate_client(request):
                log.debug('Client authentication failed, %r.', request)
                raise errors.InvalidClientError(request=request)
        elif not self.request_validator.authenticate_client_id(request.client_id, request):
            # REQUIRED, if the client is not authenticating with the
            # authorization server as described in Section 3.2.1.
            # https://tools.ietf.org/html/rfc6749#section-3.2.1
            log.debug('Client authentication failed, %r.', request)
            raise errors.InvalidClientError(request=request)

        if not hasattr(request.client, 'client_id'):
            raise NotImplementedError('Authenticate client must set the '
                                      'request.client.client_id attribute '
                                      'in authenticate_client.')

        request.client_id = request.client_id or request.client.client_id

        # Ensure client is authorized use of this grant type
        self.validate_grant_type(request)

        # REQUIRED. The authorization code received from the
        # authorization server.
        if not self.request_validator.validate_code(request.client_id,
                                                    request.code, request.client, request):
            log.debug('Client, %r (%r), is not allowed access to scopes %r.',
                      request.client_id, request.client, request.scopes)
            raise errors.InvalidGrantError(request=request)

        # OPTIONAL. Validate PKCE code_verifier
        challenge = self.request_validator.get_code_challenge(request.code, request)

        if challenge is not None:
            if request.code_verifier is None:
                raise errors.MissingCodeVerifierError(request=request)

            challenge_method = self.request_validator.get_code_challenge_method(request.code, request)
            if challenge_method is None:
                raise errors.InvalidGrantError(request=request, description="Challenge method not found")

            if challenge_method not in self._code_challenge_methods:
                raise errors.ServerError(
                    description="code_challenge_method {} is not supported.".format(challenge_method),
                    request=request
                )

            if not self.validate_code_challenge(challenge,
                                                challenge_method,
                                                request.code_verifier):
                log.debug('request provided a invalid code_verifier.')
                raise errors.InvalidGrantError(request=request)
        elif self.request_validator.is_pkce_required(request.client_id, request) is True:
            if request.code_verifier is None:
                raise errors.MissingCodeVerifierError(request=request)
            raise errors.InvalidGrantError(request=request, description="Challenge not found")

        for attr in ('user', 'scopes'):
            if getattr(request, attr, None) is None:
                log.debug('request.%s was not set on code validation.', attr)

        # REQUIRED, if the "redirect_uri" parameter was included in the
        # authorization request as described in Section 4.1.1, and their
        # values MUST be identical.
        if request.redirect_uri is None:
            request.using_default_redirect_uri = True
            request.redirect_uri = self.request_validator.get_default_redirect_uri(
                request.client_id, request)
            log.debug('Using default redirect_uri %s.', request.redirect_uri)
            if not request.redirect_uri:
                raise errors.MissingRedirectURIError(request=request)
        else:
            request.using_default_redirect_uri = False
            log.debug('Using provided redirect_uri %s', request.redirect_uri)

        if not self.request_validator.confirm_redirect_uri(request.client_id, request.code,
                                                           request.redirect_uri, request.client,
                                                           request):
            log.debug('Redirect_uri (%r) invalid for client %r (%r).',
                      request.redirect_uri, request.client_id, request.client)
            raise errors.MismatchingRedirectURIError(request=request)

        for validator in self.custom_validators.post_token:
            validator(request)