错误与警告

以下是一些常见的错误和警告,以及如何处理它们。

SecurityWarning

Added in version 1.2.0.

You may encounter a SecurityWarning when using potentially unsafe algorithms or generating insecure keys. These warnings do not interrupt the execution of your application — they are simply printed to standard output (e.g., your terminal).

If you prefer to suppress these warnings, you can use Python’s built-in warnings module:

import warnings
from joserfc.errors import SecurityWarning

warnings.simplefilter('ignore', SecurityWarning)

With this configuration, SecurityWarning messages will no longer appear. Be cautious when suppressing these warnings, as they are meant to alert you to potentially insecure practices.

pytest

When running unit tests with pytest, you may want to ignore security warnings. In that case, you can configure it in your pyproject.toml file:

pyproject.toml
[tool.pytest.ini_options]
filterwarnings = [
    "ignore::joserfc.errors.SecurityWarning",
]

UnsupportedAlgorithmError

在 1.1.0 版本发生变更: From version 1.1.0, an UnsupportedAlgorithmError will be raised instead of a ValueError.

By default, ONLY recommended 算法 are allowed. With non recommended algorithms, you may encounter the UnsupportedAlgorithmError error.

>>> from joserfc import jws
>>> from joserfc.jwk import OctKey
>>> key = OctKey.generate_key()
>>> jws.serialize_compact({"alg": "HS384"}, b"payload", key)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../joserfc/jws.py", line 112, in serialize_compact
    alg: JWSAlgModel = registry.get_alg(protected["alg"])
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../joserfc/_rfc7515/registry.py", line 60, in get_alg
    raise UnsupportedAlgorithmError(f'Algorithm of "{name}" is not recommended')
joserfc.errors.UnsupportedAlgorithmError: unsupported_algorithm: Algorithm of "HS384" is not recommended

Because "HS384" is not a recommended algorithm, it is not allowed by default. You SHOULD enable it manually by passing an algorithms parameter:

>>> jws.serialize_compact({"alg": "HS384"}, b"payload", key, algorithms=["HS384"])

Developers can also apply the registry parameter to resolve this issue. Here is an example of using 注册表.

>>> from joserfc import jws
>>> from joserfc.jwk import OctKey
>>> key = OctKey.import_key("your-secret-key")
>>> registry = jws.JWSRegistry(algorithms=["HS384"])
>>> jws.serialize_compact({"alg": "HS384"}, b"payload", key, registry=registry)
'eyJhbGciOiJIUzM4NCJ9.cGF5bG9hZA.TJEvlp74g89hNRNGNZxCQvB7YDEAWP5vFAjgu1O9Qr5BLMj0NtvbxvYkVYPGp-xQ'