Skip to content

Commit 488c596

Browse files
committed
update readme
1 parent 2cb3b46 commit 488c596

File tree

1 file changed

+186
-0
lines changed

1 file changed

+186
-0
lines changed

README.md

Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,189 @@ JWT utilities module for Ellar.
1919
```shell
2020
$(venv) pip install ellar-jwt
2121
```
22+
23+
## Usage
24+
25+
Import `JWTModule`:
26+
27+
```python
28+
from ellar.common import Module
29+
from ellar_jwt import JWTModule
30+
31+
32+
@Module(
33+
modules=[JWTModule.setup(signing_secret_key='my_private_key')]
34+
)
35+
class AuthModule:
36+
pass
37+
38+
```
39+
40+
Inject `JWTService` where its needed as shown below
41+
42+
```python
43+
from ellar_jwt import JWTService
44+
from ellar.di import injectable
45+
46+
47+
@injectable()
48+
class AuthService:
49+
def __init__(self, jwt_service: JWTService) -> None:
50+
self.jwt_service = jwt_service
51+
52+
```
53+
54+
## JWTModule Setup
55+
There are two ways in config JWTModule
56+
- **setup**:
57+
`JWTModule.setup` takes some parameters that allows instance configuration of the `JWTConfiguration` schema required by the `JWTService`
58+
59+
For example:
60+
```python
61+
from ellar.common import Module
62+
from ellar_jwt import JWTModule
63+
64+
65+
@Module(
66+
modules=[JWTModule.setup(signing_secret_key='my_private_key', issuer='https://google.com')]
67+
)
68+
class AuthModule:
69+
pass
70+
```
71+
- **register**:
72+
73+
`JWTModule.register` allow you to provide JWT configuration in Ellar application config object using `JWT_CONFIG` key.
74+
The register function will create a `ModuleSetup` object that will inject application `config` to a JWT config factory
75+
76+
for example:
77+
```python
78+
# config.py
79+
import json
80+
from datetime import timedelta
81+
82+
class DevelopmentConfig:
83+
JWT_CONFIG = {
84+
'algorithm':"HS256", # allow_algorithms=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"]
85+
'leeway': 0, # t.Union[float, int, timedelta]
86+
87+
'signing_secret_key': 'secret', # secret or private key
88+
'verifying_secret_key': "", # public key
89+
'audience': None,
90+
91+
'issuer': None,
92+
'jwk_url': None,
93+
94+
'jti': "jti",
95+
'lifetime': timedelta(minutes=5), # token lifetime, this will example in 5 mins
96+
97+
'json_encoder':json.JSONEncoder # token lifetime, this will example
98+
}
99+
```
100+
In `auth/module.py`
101+
```python
102+
from ellar.common import Module
103+
from ellar_jwt import JWTModule
104+
105+
106+
@Module(
107+
modules=[JWTModule.register_setup()]
108+
)
109+
class AuthModule:
110+
pass
111+
```
112+
113+
114+
## JWT Configuration Options
115+
```python
116+
import json
117+
from datetime import timedelta
118+
119+
120+
JWT_CONFIG = {
121+
'algorithm':"HS256", # allow_algorithms=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"]
122+
'leeway': 0, # t.Union[float, int, timedelta]
123+
124+
'signing_secret_key': 'secret', # secret or private key
125+
'verifying_secret_key': "", # public key
126+
'audience': None,
127+
128+
'issuer': None,
129+
'jwk_url': None,
130+
131+
'jti': "jti",
132+
'lifetime': timedelta(minutes=5), # token lifetime, this will example in 5 mins
133+
134+
'json_encoder':json.JSONEncoder # token lifetime, this will example
135+
}
136+
```
137+
138+
- ### `lifetime`
139+
A `datetime.timedelta` object is employed to define the validity duration of the tokens.
140+
When generating a token, this `timedelta` value is combined with the present `UTC` time to establish the default `exp` claim value for the token.
141+
142+
- ### `algorithm`
143+
The chosen algorithm from the `PyJWT` library governs the signing and verification procedures for tokens.
144+
For symmetric HMAC signing and verification, you have the option to use the following algorithms: `HS256`, `HS384`, and `HS512`.
145+
In the case of an HMAC algorithm, the signing_secret_key serves both as the signing and verifying key, rendering the `verifying_secret_key` setting redundant.
146+
On the other hand, for asymmetric RSA signing and verification, you can opt for the following algorithms: `RS256`, `RS384`, and `RS512`.
147+
In this scenario, selecting an RSA algorithm mandates configuring the `signing_secret_key` setting with an RSA private key string. Correspondingly, the `verifying_secret_key` setting must contain an RSA public key string
148+
149+
- ### `signing_secret_key`
150+
The signing key utilized for signing the content of generated tokens has distinct requirements based on the signing protocol.
151+
For HMAC signing, it should be a randomly generated string containing at least as many bits as dictated by the signing protocol.
152+
Conversely, for RSA signing, it should be a string encompassing an RSA private key with a length of 2048 bits or more.
153+
As Simple JWT defaults to 256-bit HMAC signing, the `signing_secret_key` setting automatically takes on the value of your django project's `SECRET_KEY`.
154+
While this default is practical, it's advisable for developers to modify this setting to a value separate from the django project's secret key.
155+
This adjustment facilitates easier token signing key changes if the key is ever compromised.
156+
157+
- ### `verifying_secret_key`
158+
The verification key is employed to authenticate the contents of generated tokens.
159+
In case an HMAC algorithm is indicated by the `algorithm` setting, the `verifying_secret_key` configuration is disregarded, and the `signing_secret_key` setting value will be utilized.
160+
However, if an RSA algorithm is designated by the `algorithm` setting, the `verifying_secret_key` parameter must be populated with an RSA public key string
161+
162+
- ### `audience`
163+
The audience claim is incorporated into generated tokens and/or verified within decoded tokens.
164+
If configured as `None`, this element is omitted from tokens and isn't subjected to validation.
165+
166+
- ### `issuer`
167+
The issuer claim is added to generated tokens and/or validated within decoded tokens.
168+
If configured as `None`, this attribute is omitted from tokens and isn't subjected to validation.
169+
170+
- ### `jwk_url`
171+
The JWK_URL serves the purpose of dynamically retrieving the required public keys for token signature verification.
172+
For instance, with Auth0, you could configure it as 'https://yourdomain.auth0.com/.well-known/jwks.json'.
173+
If set to `None`, this field is omitted from the token backend and remains inactive during validation.
174+
175+
- ### `leeway`
176+
Leeway provides a buffer for the expiration time, which can be defined as an integer representing seconds or a datetime.timedelta object.
177+
For further details, please consult the following link: https://pyjwt.readthedocs.io/en/latest/usage.html#expiration-time-claim-exp
178+
179+
- ### `jti`
180+
The claim designated for storing a token's unique identifier, which is utilized to distinguish revoked tokens within the blacklist application.
181+
There might be instances where an alternative claim other than the default "jti" claim needs to be employed for storing this value
182+
183+
- ### `json_encoder`
184+
JSON Encoder class that will be used by the `PYJWT` to encode the `jwt_payload`.
185+
186+
187+
188+
## API Spec
189+
190+
The `JwtService` uses [PYJWT](https://pypi.org/project/PyJWT/) underneath.
191+
192+
### _jwt_service.sign(payload: dict, headers: Dict[str, t.Any] = None) -> str_
193+
Creates a jwt token for the provided payload
194+
195+
### _jwt_service.sign_async(payload: dict, headers: Dict[str, t.Any] = None) -> str_
196+
Async action for `jwt_service.sign`
197+
198+
### _jwt_service.decode(token: str, verify: bool = True) -> t.Dict[str, t.Any]:_
199+
Verifies and decodes provided token. And raises JWTException exception if token is invalid or expired
200+
201+
### _jwt_service.decode_async(token: str, verify: bool = True) -> t.Dict[str, t.Any]:_
202+
Async action for `jwt_service.decode`
203+
204+
205+
## License
206+
207+
Ellar is [MIT licensed](LICENSE).

0 commit comments

Comments
 (0)