當前位置: 首頁>>代碼示例>>Python>>正文


Python jwt.decode方法代碼示例

本文整理匯總了Python中jose.jwt.decode方法的典型用法代碼示例。如果您正苦於以下問題:Python jwt.decode方法的具體用法?Python jwt.decode怎麽用?Python jwt.decode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在jose.jwt的用法示例。


在下文中一共展示了jwt.decode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: login_required

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def login_required(f):
    '''
    This decorator checks the header to ensure a valid token is set
    '''
    @wraps(f)
    def func(*args, **kwargs):
        try:
            if 'authorization' not in request.headers:
                abort(404, message="You need to be logged in to access this resource")
            token = request.headers.get('authorization')
            payload = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
            user_id = payload['id']
            g.user = User.find(user_id)
            if g.user is None:
               abort(404, message="The user id is invalid")
            return f(*args, **kwargs)
        except JWTError as e:
            abort(400, message="There was a problem while trying to parse your token -> {}".format(e.message))
    return func 
開發者ID:afropolymath,項目名稱:papers,代碼行數:21,代碼來源:decorators.py

示例2: extract_jwt

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def extract_jwt(token, crypto_key, is_trusted=False, use_crypto=False):
    # type: (str, str, bool, bool) -> Dict[str, str]
    """Extract the claims from the validated JWT. """
    # first split and convert the jwt.
    if not token or not crypto_key:
        return {}
    if is_trusted:
        return VerifyJWT.extract_assertion(token)
    if use_crypto:
        return VerifyJWT.validate_and_extract_assertion(
            token,
            decipher_public_key(crypto_key.encode('utf8')))
    else:
        key = ecdsa.VerifyingKey.from_string(
            base64.urlsafe_b64decode(
                repad(crypto_key.encode('utf8')))[-64:],
            curve=ecdsa.NIST256p
        )
        return jwt.decode(token,
                          dict(keys=[key]),
                          options=dict(
                              verify_aud=False,
                              verify_sub=False,
                              verify_exp=False,
                          )) 
開發者ID:mozilla-services,項目名稱:autopush,代碼行數:27,代碼來源:utils.py

示例3: user_data

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def user_data(self, access_token, *args, **kwargs):
        """Get claimed user data from the JWT formatted access token."""
        decoded_access_token = jwt.decode(
            access_token,
            self._get_jwks_keys(),
            # We must skip verifications as edx does [1].
            # [1] https://github.com/edx/auth-backends/blob/6bf9d856c8e4cc4c1a72f67158468f8c94e3fca1/auth_backends/backends.py#L312 # noqa pylint: disable=line-too-long
            options={
                "verify_signature": False,
                "verify_aud": False,
                "verify_iat": False,
                "verify_exp": False,
                "verify_nbf": False,
                "verify_iss": False,
                "verify_sub": False,
                "verify_jti": False,
                "verify_at_hash": False,
                "leeway": 0,
            },
        )
        return {
            key: decoded_access_token[key]
            for key in EDX_USER_PROFILE_TO_DJANGO
            if key in decoded_access_token
        } 
開發者ID:openfun,項目名稱:richie,代碼行數:27,代碼來源:backends.py

示例4: decode_token

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def decode_token(self, token, key, algorithms=['RS256'], **kwargs):
        """
        A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data
        structure that represents a cryptographic key.  This specification
        also defines a JWK Set JSON data structure that represents a set of
        JWKs.  Cryptographic algorithms and identifiers for use with this
        specification are described in the separate JSON Web Algorithms (JWA)
        specification and IANA registries established by that specification.

        https://tools.ietf.org/html/rfc7517

        :param token:
        :param key:
        :param algorithms:
        :return:
        """

        return jwt.decode(token, key, algorithms=algorithms,
                          audience=self.client_id, **kwargs) 
開發者ID:marcospereirampj,項目名稱:python-keycloak,代碼行數:21,代碼來源:keycloak_openid.py

示例5: test_no_alg

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def test_no_alg(self, claims, key):
        token = jwt.encode(claims, key, algorithm='HS384')
        b64header, b64payload, b64signature = token.split('.')
        header_json = base64.urlsafe_b64decode(b64header.encode('utf-8'))
        header = json.loads(header_json.decode('utf-8'))
        del header['alg']
        bad_header_json_bytes = json.dumps(header).encode('utf-8')
        bad_b64header_bytes = base64.urlsafe_b64encode(bad_header_json_bytes)
        bad_b64header_bytes_short = bad_b64header_bytes.replace(b'=', b'')
        bad_b64header = bad_b64header_bytes.decode('utf-8')
        bad_token = '.'.join([bad_b64header, b64payload, b64signature])
        with pytest.raises(JWTError):
            jwt.decode(
                token=bad_token,
                key=key,
                algorithms=[]) 
開發者ID:mpdavis,項目名稱:python-jose,代碼行數:18,代碼來源:test_jwt.py

示例6: test_exp_skip

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def test_exp_skip(self, key):

        exp = datetime.utcnow() - timedelta(seconds=5)

        claims = {
            'exp': exp
        }

        token = jwt.encode(claims, key)

        with pytest.raises(JWTError):
            jwt.decode(token, key)

        options = {
            'verify_exp': False
        }

        jwt.decode(token, key, options=options) 
開發者ID:mpdavis,項目名稱:python-jose,代碼行數:20,代碼來源:test_jwt.py

示例7: validate_assertion

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def validate_assertion(assertion):
    """Checks that the JWT assertion is valid (properly signed, for the
    correct audience) and if so, returns strings for the requesting user's
    email and a persistent user ID. If not valid, returns None for each field.
    """
    from jose import jwt

    try:
        info = jwt.decode(
            assertion,
            certs(),
            algorithms=['ES256'],
            audience=audience()
            )
        return info['email'], info['sub']
    except Exception as e:
        print('Failed to validate assertion: {}'.format(e), file=sys.stderr)
        return None, None
# [END getting_started_auth_validate_assertion]


# [START getting_started_auth_front_controller] 
開發者ID:GoogleCloudPlatform,項目名稱:getting-started-python,代碼行數:24,代碼來源:main.py

示例8: __get_jwks_key

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def __get_jwks_key(self, jwks_uri, **kwargs):
        """Get from jwks_ui all the JWK keys required to decode JWT Token.

        Parameters
        ----------
        jwks_uri : string
            The URL where to gather JWKS key
        kwargs : Dict
            The constructor parameters
        """
        jwks_key = kwargs.pop('jwks_key', None)
        if not jwks_key:
            res = self._session.get(jwks_uri)
            res.raise_for_status()
            jwks_key = res.json()

        self.jwks_key_set = None
        self.jwks_key = None
        if 'keys' in jwks_key:
            self.jwks_key_set = {}
            for jwks in jwks_key['keys']:
                self.jwks_key_set[jwks['kid']] = jwks
        else:
            self.jwks_key = jwks_key 
開發者ID:Kyria,項目名稱:EsiPy,代碼行數:26,代碼來源:security.py

示例9: __get_basic_auth_header

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def __get_basic_auth_header(self):
        """Return the Basic Authorization header for oauth if secret_key exists

        Returns
        -------
        type
            A dictionary that contains the Basic Authorization key/value,
            or {} if secret_key is None

        """
        if self.secret_key is None:
            return {}

        # encode/decode for py2/py3 compatibility
        auth_b64 = "%s:%s" % (self.client_id, self.secret_key)
        auth_b64 = base64.b64encode(auth_b64.encode('utf-8'))
        auth_b64 = auth_b64.decode('utf-8')

        return {'Authorization': 'Basic %s' % auth_b64} 
開發者ID:Kyria,項目名稱:EsiPy,代碼行數:21,代碼來源:security.py

示例10: middleware

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def middleware(self, request, handler):
        token = request.headers.get('Authorization')
        if token and token.startswith('Bearer'):
            token = token[7:]
        else:
            token = request.rel_url.query.get('token')
            if not token:
                token = request.headers.get('token')
        request.verified = False

        if token:
            try:
                payload = self.decode(token)
                request.verified = True
            except jwt.JWTError:
                raise web.HTTPUnauthorized()
        else:
            payload = {}
        request.session = payload
        return await handler(request) 
開發者ID:dvhb,項目名稱:dvhb-hybrid,代碼行數:22,代碼來源:jwt.py

示例11: get_current_user

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def get_current_user(
    db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)
) -> models.User:
    try:
        payload = jwt.decode(
            token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
        )
        token_data = schemas.TokenPayload(**payload)
    except (jwt.JWTError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
        )
    user = crud.user.get(db, id=token_data.sub)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user 
開發者ID:tiangolo,項目名稱:full-stack-fastapi-postgresql,代碼行數:19,代碼來源:deps.py

示例12: get_user_details

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def get_user_details(self, response):
        # Obtain JWT and the keys to validate the signature
        id_token = response.get("id_token")
        jwks = request.urlopen(
            "https://" + self.setting("DOMAIN") + "/.well-known/jwks.json"
        )
        issuer = "https://" + self.setting("DOMAIN") + "/"
        audience = self.setting("KEY")  # CLIENT_ID
        payload = jwt.decode(
            id_token,
            jwks.read(),
            algorithms=["RS256"],
            audience=audience,
            issuer=issuer,
        )
        first_name, last_name = (payload.get("name") or " ").split(" ", 1)
        return {
            "username": payload.get("nickname") or "",
            "first_name": first_name,
            "last_name": last_name,
            "picture": payload.get("picture") or "",
            "user_id": payload.get("sub") or "",
            "email": payload.get("email") or "",
        } 
開發者ID:PacktPublishing,項目名稱:Django-3-Web-Development-Cookbook-Fourth-Edition,代碼行數:26,代碼來源:backends.py

示例13: verify_token

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def verify_token(self,token,id_name,token_use):
        kid = jwt.get_unverified_header(token).get('kid')
        unverified_claims = jwt.get_unverified_claims(token)
        token_use_verified = unverified_claims.get('token_use') == token_use
        if not token_use_verified:
            raise TokenVerificationException('Your {} token use could not be verified.')
        hmac_key = self.get_key(kid)
        try:
            verified = jwt.decode(token,hmac_key,algorithms=['RS256'],
                   audience=unverified_claims.get('aud'),
                   issuer=unverified_claims.get('iss'))
        except JWTError:
            raise TokenVerificationException('Your {} token could not be verified.')
        setattr(self,id_name,token)
        return verified 
開發者ID:capless,項目名稱:warrant,代碼行數:17,代碼來源:__init__.py

示例14: valid_jwt_token

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def valid_jwt_token(token):
    try:
        res = jwt.decode(token, jwt_secret, algorithms=['HS256'])
        print (res)
        return True
    except JWSError:
        return False 
開發者ID:comsysto,項目名稱:github-pages-basic-auth-proxy,代碼行數:9,代碼來源:proxy.py

示例15: get_user_details

# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import decode [as 別名]
def get_user_details(self, response):
        # Obtain JWT and the keys to validate the signature
        id_token = response.get('id_token')
        jwks = request.urlopen('https://' + self.setting('DOMAIN') + '/.well-known/jwks.json')
        issuer = 'https://' + self.setting('DOMAIN') + '/'
        audience = self.setting('KEY')  # CLIENT_ID
        payload = jwt.decode(id_token, jwks.read(), algorithms=['RS256'], audience=audience, issuer=issuer)
        return {'username': payload['nickname'],
                'first_name': payload['name'],
                'picture': payload['picture'],
                'user_id': payload['sub'],
                'email': payload['email']} 
開發者ID:auth0-samples,項目名稱:auth0-django-web-app,代碼行數:14,代碼來源:auth0backend.py


注:本文中的jose.jwt.decode方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。