PyJWT:自定义标头从jwt标头中删除类型

2024-09-28 01:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从jwt头中删除字典值"typ": "JWT"?我试过以下方法

jwt.encode(
    {
        "iat": 1588108543,
        "exp": 1588112143,
        "ehts": "...",
        "edts": "...."
    },
    privateKey,
    algorithm='RS256',
    headers={"alg": "RS256"})

但是仍然在jwt头中获得typ。我正在使用pyjwt python库

输出:

eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE1ODgxMDg1NDMsImV4cCI6MTU4ODExMjE0MywiZWh0cyI6ImNvbnRlbnQtdHlwZTthdXRob3JpemF0aW9uO3gtZGV2aWNlLWlkO2FjY2VwdC1sYW5ndWFnZTtib2R5IiwiZWR0cyI6IjgwNmQ2N2JhYzdmY2ZjNDQ5ZmJkZTllNDExOGFkODY5NWJlZjFmMzQ3ZTIzN2E1YjgyZGQ0MThlM2JhNjE2ODUifQ.WsKUWYoyrEhd78kcyfoBk2cuqHFF_9F0oLpsnEoV5lD7yTw8Cu4Z9TgHPrLgEeVOSXXKNu45CBbzi2v3YhQOS7vLXDEHWI6BpoGjNFymsaVqsCA4bUmDtZ9mq2ugyeeIfZ5E6L0ywBF3BYAy8DnxRk8yyHSQCkuQm4W8AZnwXWzefdz5dCSljzTQtLli0x_s1hqOlYtAXtPvHQbx4OYPYkARrYHjRatiqyXECYNcgQGxbMs_knF7vgSk7uf0uSoJvbdpjPBd4xpnLbAWMHeDlhtG834r2bCFFKZJARGCfXZW_0y8PyJGNhscKIpg7BIfiEAgqIlcFMX3N0qbYaYl9w

jwt

谢谢


Tags: 方法字典jwtalgorithmencodeheaderspyjwtalg
2条回答

只需将PyJWS.header_type设置为False | None。确保定义实际需要的标题

jwt.api_jws.PyJWS.header_typ = False
jwt.encode(..., headers={"alg": "HS512"})

扩展PyJWS.encode可能会覆盖默认标头

import json
try:
    # import required by mypy to perform type checking, not used for normal execution
    from typing import Callable, Dict, List, Optional, Union # NOQA
except ImportError:
    pass

from jwt.algorithms import (
    Algorithm, get_default_algorithms, has_crypto, requires_cryptography  # NOQA
)
from jwt.utils import base64url_decode, base64url_encode, force_bytes, merge_dict
class MyPyJWS(PyJWS):

    def encode(self,
               payload,  # type: Union[Dict, bytes]
               key,  # type: str
               algorithm='HS256',  # type: str
               headers=None,  # type: Optional[Dict]
               json_encoder=None  # type: Optional[Callable]
               ):
        segments = []

        if algorithm is None:
            algorithm = 'none'

        if algorithm not in self._valid_algs:
            pass

        # Header
        header = {'alg': algorithm}

        if headers:
            self._validate_headers(headers)
            header.update(headers)

        json_header = force_bytes(
            json.dumps(
                header,
                separators=(',', ':'),
                cls=json_encoder
            )
        )

        segments.append(base64url_encode(json_header))
        segments.append(base64url_encode(payload))

        # Segments
        signing_input = b'.'.join(segments)
        try:
            alg_obj = self._algorithms[algorithm]
            key = alg_obj.prepare_key(key)
            signature = alg_obj.sign(signing_input, key)

        except KeyError:
            if not has_crypto and algorithm in requires_cryptography:
                raise NotImplementedError(
                    "Algorithm '%s' could not be found. Do you have cryptography "
                    "installed?" % algorithm
                )
            else:
                raise NotImplementedError('Algorithm not supported')

        segments.append(base64url_encode(signature))

        return b'.'.join(segments)

import jwt
encoded_jwt = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')
print(encoded_jwt)
json_payload = json.dumps(
            {'some': 'payload'},
            separators=(',', ':')
        ).encode('utf-8')
encoded_jwt = MyPyJWS().encode(json_payload , 'secret', algorithm='HS256')
print(encoded_jwt)

相关问题 更多 >

    热门问题