lepture / authlib

The ultimate Python library in building OAuth, OpenID Connect clients and servers. JWS,JWE,JWK,JWA,JWT included.
https://authlib.org/
BSD 3-Clause "New" or "Revised" License
4.39k stars 436 forks source link

Too slow to generate id token with RSA #648

Closed w-mj closed 2 months ago

w-mj commented 2 months ago

When generating id token, jwt.encode() calls jws.serialize_compact() to serialize id token. Then jws.serialize_compact() calls _prepare_algorithm_key to get the key.

https://github.com/lepture/authlib/blob/610622e54b6cbc810ad9fda97569f13401614348/authlib/jose/rfc7515/jws.py#L62

But _prepare_algorithm_key() always construct a new key object, if the type of key is RSA, then when signing id token, get_private_key() will be called, RSA_check_key() will also be called. https://github.com/lepture/authlib/blob/610622e54b6cbc810ad9fda97569f13401614348/authlib/jose/rfc7515/jws.py#L257

Unfortunately, in OpenSSL 3.0.0, RSA_check_key() become too slow. In my system, this procedure may consume 300ms in every request, it is unacceptable.

I wonder if the key should be cached in jwt object instead of build and check RSA key in every request, or any method to close RSA key checking?

w-mj commented 2 months ago

Make OpenIDConnect.get_jwt_config() return a Key object instead of KeySet can solve the problem.