Use request information to validate JWT
961214
def verify_http_auth_token(self) -> bool:
        
        authorization_token = self.get_http_token()
        if authorization_token is not None:
            if self.verify_token(authorization_token):
                if self.data is not None:
                    self.data = self.data['data']
                    return True
                return False
            else:
                return False
        return False
242329
def verify_fresh_jwt_in_request():
    
    if request.method not in config.exempt_methods:
        jwt_data = _decode_jwt_from_request(request_type='access')
        ctx_stack.top.jwt = jwt_data
        fresh = jwt_data['fresh']
        if isinstance(fresh, bool):
            if not fresh:
                raise FreshTokenRequired('Fresh token required')
        else:
            now = timegm(datetime.utcnow().utctimetuple())
            if fresh < now:
                raise FreshTokenRequired('Fresh token required')
        verify_token_claims(jwt_data)
        _load_user(jwt_data[config.identity_claim_key])
328227
async def _make_request(self, method: str, url: str, url_vars: Dict[str, str],
                            data: Any, accept: str,
                            jwt: Opt[str] = None,
                            oauth_token: Opt[str] = None,
                            ) -> Tuple[bytes, Opt[str]]:
        """"""
        if oauth_token is not None and jwt is not None:
            raise ValueError("Cannot pass both oauth_token and jwt.")
        filled_url = sansio.format_url(url, url_vars)
        if jwt is not None:
            request_headers = sansio.create_headers(
                self.requester, accept=accept,
                jwt=jwt)
        elif oauth_token is not None:
            request_headers = sansio.create_headers(
                self.requester, accept=accept,
                oauth_token=oauth_token)
        else:
            # fallback to using oauth_token
            request_headers = sansio.create_headers(
                self.requester, accept=accept,
                oauth_token=self.oauth_token)
        cached = cacheable = False
        # Can't use None as a "no body" sentinel as it's a legitimate JSON type.
        if data == b"":
            body = b""
            request_headers["content-length"] = "0"
            if method == "GET" and self._cache is not None:
                cacheable = True
                try:
                    etag, last_modified, data, more = self._cache[filled_url]
                    cached = True
                except KeyError:
                    pass
                else:
                    if etag is not None:
                        request_headers["if-none-match"] = etag
                    if last_modified is not None:
                        request_headers["if-modified-since"] = last_modified
        else:
            charset = "utf-8"
            body = json.dumps(data).encode(charset)
            request_headers['content-type'] = f"application/json; charset={charset}"
            request_headers['content-length'] = str(len(body))
        if self.rate_limit is not None:
            self.rate_limit.remaining -= 1
        response = await self._request(method, filled_url, request_headers, body)
        if not (response[0] == 304 and cached):
            data, self.rate_limit, more = sansio.decipher_response(*response)
            has_cache_details = ("etag" in response[1]
                                 or "last-modified" in response[1])
            if self._cache is not None and cacheable and has_cache_details:
                etag = response[1].get("etag")
                last_modified = response[1].get("last-modified")
                self._cache[filled_url] = etag, last_modified, data, more
        return data, more
659214
def get_jwt(self, request):
        
        try:
            authorization = request.authorization
        except ValueError:
            return None
        if authorization is None:
            return None
        authtype, token = authorization
        if authtype.lower() != self.auth_header_prefix.lower():
            return None
        return token
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
1092795
protected function validateKey()
    {
        if (\is_string($key = $this->key)) {
            if (\substr($key, 0, 7) !== 'file://') {
                $key = 'file://' . $key;
            }

            $this->key = \openssl_get_privatekey($key, $this->passphrase ?: '');
        }

        if (!\is_resource($this->key)) {
            throw new JWTException('Invalid key: Should be resource of private key', static::ERROR_KEY_INVALID);
        }
    }
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',
            )
339238
function validMethod(req, res, next) {
    if (httpMethods.indexOf(req.method) === -1) {
        res.sendStatus(405);
    } else {
        next();
    }
}
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']
761731
def is_valid_request(self, request, parameters={},
                         fake_method=None, handle_error=True):
        '''
        

        '''
        try:
            # Set the parameters to be what we were passed earlier
            # if we didn't get any passed to us now
            if not parameters and hasattr(self, 'params'):
                parameters = self.params

            method, url, headers, parameters = self.parse_request(
                request, parameters, fake_method)

            oauth_request = oauth2.Request.from_request(
                method,
                url,
                headers=headers,
                parameters=parameters)

            self.oauth_server.verify_request(
                oauth_request, self.oauth_consumer, {})

        except oauth2.MissingSignature, e:
            if handle_error:
                return False
            else:
                raise e
        # Signature was valid
        return True
572923
def post(self):
        
        #1.
        username = request.form.get("username")
        password = request.form.get("password")
        exipres  = 7200
        #expire time(seconds)
        if username and password:
            _authRes = self._getAuthentication(username, password)
        else:
            return {"msg": "invalid username or password"}
        #2.
        if _authRes:
            _payload = self._getUserData(username)
            #3.
            try:
                token = self.jwt.createJWT(_payload, expiredSeconds=exipres)
            except JWTException:
            	return {"msg": "Failed to request token"}
            else:
                return {"token": token}
        else:
            return {"msg": "Authentication failed"}
1186568
function (err, ok, state) {
        if (err) { return self.error(err); }
        if (!ok) { return self.fail(state, 403); }

        if (self._jwt) {
          self._authenticate_jwt(req, state);
        } else {
          self._authenticate_saml(req, state);
        }
      }
647788
def is_suitable(self, request):
        
        if self.key_type:
            validation = KEY_TYPE_VALIDATIONS.get( self.get_type() )
            return validation( request ) if validation else None
        return True
590549
function Parse ( token ) {
  if ( typeof token != 'string' )
      throw new Error('JWT must be a string object')

  var parts = token.split('.')

  if (!parts.every(b64url.valid))
      throw new Error('JWT contains invalid URL safe Base64 chars')
  try {
    this.header = JSON.parse( b64url.decode( parts[0] ) )
  }
  catch (e) {
      return e
  }
  if (!this.header.typ)
      throw new Error('No "typ" in JWT header')

  if (this.header.typ == 'JWS') {
    try {
      this.payload = JSON.parse( b64url.decode( parts[1] ) )
    }
    catch (e) {
        return e
    }
    this._input = parts[0] +'.'+ parts[1]
    this.signature = parts[2]
    return this

  } else if (this.header.typ == 'JWE') {
    if (parts.length != 5)
      throw new Error('Invalid JWE token, does not have 5 components')
    this._input = parts[0] +'.'+ parts[1] +'.'+ parts[2] +'.'+ parts[3]
    this._cmk = parts[1]
    this._iv = parts[2]
    this._ciphertext = parts[3]
    this.signature = parts[4]
    return this

  } else
    throw new Error('Uknownn JWT header "typ":"'+this.header.typ+'"')
}
555645
def SecurityCheck(self, func, request, *args, **kwargs):
    """"""
    if self.IAP_HEADER not in request.headers:
      return werkzeug_wrappers.Response("Unauthorized", status=401)

    jwt = request.headers.get(self.IAP_HEADER)
    try:
      request.user, _ = validate_iap.ValidateIapJwtFromComputeEngine(
          jwt, self.cloud_project_id, self.backend_service_id)
      return func(request, *args, **kwargs)

    except validate_iap.IAPValidationFailedError as e:
      # Return failure if IAP is not decoded correctly.
      logging.error("IAPWebAuthManager failed with: %s", e)
      return werkzeug_wrappers.Response("Unauthorized", status=401)
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
545965
def jwt_required(func):
    
    if inspect.isclass(func):
        apply_function_to_members(func, jwt_required)
        return func
    else:
        @functools.wraps(func)
        def deco(*a, **kw):
            if not "Authorization" in request.headers:
                abort(401, "Not Authorized")
            return func(*a, **kw)

        return deco