|
1 |
| -# fastapi-jwt-auth |
| 1 | +<h1 align="left" style="margin-bottom: 20px; font-weight: 500; font-size: 50px; color: black;"> |
| 2 | + FastAPI JWT Auth |
| 3 | +</h1> |
2 | 4 |
|
3 | 5 | [](https://travis-ci.org/IndominusByte/fastapi-jwt-auth)
|
4 | 6 | [](https://coveralls.io/github/IndominusByte/fastapi-jwt-auth?branch=master)
|
5 | 7 | [](https://badge.fury.io/py/fastapi-jwt-auth)
|
6 | 8 | [](https://pepy.tech/project/fastapi-jwt-auth)
|
7 | 9 |
|
| 10 | +--- |
| 11 | + |
8 | 12 | ## Features
|
9 | 13 | FastAPI extension that provides JWT Auth support (secure, easy to use and lightweight), if you were familiar with flask-jwt-extended this extension suitable for you because this extension inspired by flask-jwt-extended.
|
| 14 | + |
10 | 15 | - Access token and refresh token
|
11 |
| -- Token freshness will only allow fresh tokens to access endpoint |
12 |
| -- Token revoking/blacklisting |
13 |
| -- Custom token revoking |
| 16 | +- Token freshness |
| 17 | +- Token revoking |
| 18 | +- Support for adding custom claims to JSON Web Tokens |
| 19 | +- Support RSA encryption |
| 20 | +- Storing tokens in cookies and CSRF protection |
14 | 21 |
|
15 | 22 | ## Installation
|
16 |
| -```bash |
17 |
| -pip install fastapi-jwt-auth |
18 |
| -``` |
| 23 | +The easiest way to start working with this extension with pip |
19 | 24 |
|
20 |
| -## Usage |
21 |
| -### Setting `AUTHJWT_SECRET_KEY` in environment variable |
22 |
| -- For Linux, macOS, Windows Bash |
23 |
| -```bash |
24 |
| -export AUTHJWT_SECRET_KEY=secretkey |
25 |
| -``` |
26 |
| -- For Windows PowerShell |
27 | 25 | ```bash
|
28 |
| -$Env:AUTHJWT_SECRET_KEY = "secretkey" |
29 |
| -``` |
30 |
| -### Create it |
31 |
| -- Create a file `basic.py` with: |
32 |
| -```python |
33 |
| -from fastapi import FastAPI, Depends, HTTPException |
34 |
| -from fastapi_jwt_auth import AuthJWT |
35 |
| -from pydantic import BaseModel, Field |
36 |
| - |
37 |
| -app = FastAPI() |
38 |
| - |
39 |
| -class User(BaseModel): |
40 |
| - username: str = Field(...,min_length=1) |
41 |
| - password: str = Field(...,min_length=1) |
42 |
| - |
43 |
| -# Provide a method to create access tokens. The create_access_token() |
44 |
| -# function is used to actually generate the token, and you can return |
45 |
| -# it to the caller however you choose. |
46 |
| -@app.post('/login',status_code=200) |
47 |
| -def login(user: User, Authorize: AuthJWT = Depends()): |
48 |
| - if user.username != 'test' or user.password != 'test': |
49 |
| - raise HTTPException(status_code=401,detail='Bad username or password') |
50 |
| - |
51 |
| - # identity must be between string or integer |
52 |
| - access_token = Authorize.create_access_token(identity=user.username) |
53 |
| - return {"access_token": access_token} |
54 |
| - |
55 |
| -@app.get('/protected',status_code=200) |
56 |
| -def protected(Authorize: AuthJWT = Depends()): |
57 |
| - # Protect an endpoint with jwt_required, which requires a valid access token |
58 |
| - # in the request to access. |
59 |
| - Authorize.jwt_required() |
60 |
| - |
61 |
| - # Access the identity of the current user with get_jwt_identity |
62 |
| - current_user = Authorize.get_jwt_identity() |
63 |
| - return {"logged_in_as": current_user} |
64 |
| - |
| 26 | +pip install fastapi-jwt-auth |
65 | 27 | ```
|
66 |
| -### Run it |
67 |
| -Run the server with: |
68 |
| -```console |
69 |
| -$ uvicorn basic:app --host 0.0.0.0 |
70 | 28 |
|
71 |
| -INFO: Started server process [4235] |
72 |
| -INFO: Waiting for application startup. |
73 |
| -INFO: Application startup complete. |
74 |
| -INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) |
75 |
| -``` |
76 |
| -### Access it |
77 |
| -To access a jwt_required protected url, all we have to do is send in the JWT with the request. By default, this is done with an authorization header that looks like: |
| 29 | +If you want to use asymmetric (public/private) key signing algorithms, include the <b>asymmetric</b> extra requirements. |
78 | 30 | ```bash
|
79 |
| -Authorization: Bearer <access_token> |
80 |
| -``` |
81 |
| -We can see this in action using CURL: |
82 |
| -```console |
83 |
| -$ curl http://localhost:8000/protected |
84 |
| - |
85 |
| -{"detail":"Missing Authorization Header"} |
86 |
| - |
87 |
| -$ curl -H "Content-Type: application/json" -X POST \ |
88 |
| - -d '{"username":"test","password":"test"}' http://localhost:8000/login |
89 |
| - |
90 |
| -"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1OTczMzMxMzMsIm5iZiI6MTU5NzMzMzEzMywianRpIjoiNDczY2ExM2ItOWI1My00NDczLWJjZTctMWZiOWMzNTlmZmI0IiwiZXhwIjoxNTk3MzM0MDMzLCJpZGVudGl0eSI6InRlc3QiLCJ0eXBlIjoiYWNjZXNzIiwiZnJlc2giOmZhbHNlfQ.42CusQo6nsLxOk6bBUP1vnVX-REx4ZYBYYIjYChWf0c" |
91 |
| - |
92 |
| -$ export TOKEN=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1OTczMzMxMzMsIm5iZiI6MTU5NzMzMzEzMywianRpIjoiNDczY2ExM2ItOWI1My00NDczLWJjZTctMWZiOWMzNTlmZmI0IiwiZXhwIjoxNTk3MzM0MDMzLCJpZGVudGl0eSI6InRlc3QiLCJ0eXBlIjoiYWNjZXNzIiwiZnJlc2giOmZhbHNlfQ.42CusQo6nsLxOk6bBUP1vnVX-REx4ZYBYYIjYChWf0c |
93 |
| - |
94 |
| -$ curl -H "Authorization: Bearer $TOKEN" http://localhost:8000/protected |
95 |
| - |
96 |
| -{"logged_in_as":"test"} |
97 |
| -``` |
98 |
| -## Extract Token |
99 |
| -Access all URL to see what the result |
100 |
| -```python |
101 |
| -from fastapi import FastAPI, Depends, HTTPException |
102 |
| -from fastapi_jwt_auth import AuthJWT |
103 |
| -from pydantic import BaseModel, Field |
104 |
| - |
105 |
| -app = FastAPI() |
106 |
| - |
107 |
| -class User(BaseModel): |
108 |
| - username: str = Field(...,min_length=1) |
109 |
| - password: str = Field(...,min_length=1) |
110 |
| - |
111 |
| -@app.post('/login',status_code=200) |
112 |
| -def login(user: User, Authorize: AuthJWT = Depends()): |
113 |
| - if user.username != 'test' or user.password != 'test': |
114 |
| - raise HTTPException(status_code=401,detail='Bad username or password') |
115 |
| - |
116 |
| - access_token = Authorize.create_access_token(identity=user.username) |
117 |
| - return access_token |
118 |
| - |
119 |
| -# Returns the JTI (unique identifier) of an encoded JWT |
120 |
| -@app.get('/get-jti',status_code=200) |
121 |
| -def get_jti(Authorize: AuthJWT = Depends()): |
122 |
| - access_token = Authorize.create_access_token(identity='test') |
123 |
| - return Authorize.get_jti(encoded_token=access_token) |
124 |
| - |
125 |
| -# this will return the identity of the JWT that is accessing this endpoint. |
126 |
| -# If no JWT is present, `None` is returned instead. |
127 |
| -@app.get('/get-jwt-identity',status_code=200) |
128 |
| -def get_jwt_identity(Authorize: AuthJWT = Depends()): |
129 |
| - Authorize.jwt_optional() |
130 |
| - |
131 |
| - current_user = Authorize.get_jwt_identity() |
132 |
| - return {"logged_in_as": current_user} |
133 |
| - |
134 |
| -# this will return the python dictionary which has all |
135 |
| -# of the claims of the JWT that is accessing the endpoint. |
136 |
| -# If no JWT is currently present, return None instead |
137 |
| -@app.get('/get-raw-jwt',status_code=200) |
138 |
| -def get_raw_jwt(Authorize: AuthJWT = Depends()): |
139 |
| - Authorize.jwt_optional() |
140 |
| - |
141 |
| - token = Authorize.get_raw_jwt() |
142 |
| - return {"token": token} |
143 |
| -``` |
144 |
| - |
145 |
| -## Configuration Options (env) |
146 |
| -- `AUTHJWT_ACCESS_TOKEN_EXPIRES`<br/> |
147 |
| -How long an access token should live before it expires. If you not define in env variable |
148 |
| -default value is `15 minutes`. Or you can custom with value `int` (seconds), example |
149 |
| -`AUTHJWT_ACCESS_TOKEN_EXPIRES=300` its mean access token expired in 5 minute |
150 |
| - |
151 |
| -- `AUTHJWT_REFRESH_TOKEN_EXPIRES`<br/> |
152 |
| -How long a refresh token should live before it expires. If you not define in env variable |
153 |
| -default value is `30 days`. Or you can custom with value `int` (seconds), example |
154 |
| -`AUTHJWT_REFRESH_TOKEN_EXPIRES=86400` its mean refresh token expired in 1 day |
155 |
| - |
156 |
| -- `AUTHJWT_BLACKLIST_ENABLED`<br/> |
157 |
| -Enable/disable token revoking. Default value is None, for enable blacklist token: `AUTHJWT_BLACKLIST_ENABLED=true` |
158 |
| - |
159 |
| -- `AUTHJWT_SECRET_KEY`<br/> |
160 |
| -The secret key needed for symmetric based signing algorithms, such as HS*. If this is not set `raise RuntimeError`. |
161 |
| - |
162 |
| -- `AUTHJWT_ALGORITHM`<br/> |
163 |
| -Which algorithms are allowed to decode a JWT. Default value is `HS256` |
164 |
| - |
165 |
| -## Configuration (pydantic or list[tuple]) |
166 |
| -You can convert and validate type data from dotenv through pydantic (BaseSettings) |
167 |
| -```python |
168 |
| -from fastapi_jwt_auth import AuthJWT |
169 |
| -from pydantic import BaseSettings |
170 |
| -from datetime import timedelta |
171 |
| -from typing import Literal |
172 |
| - |
173 |
| -# dotenv file parsing requires python-dotenv to be installed |
174 |
| -# This can be done with either pip install python-dotenv |
175 |
| -class Settings(BaseSettings): |
176 |
| - authjwt_access_token_expires: timedelta = timedelta(minutes=15) |
177 |
| - authjwt_refresh_token_expires: timedelta = timedelta(days=30) |
178 |
| - # literal type only available for python 3.8 |
179 |
| - authjwt_blacklist_enabled: Literal['true','false'] |
180 |
| - authjwt_secret_key: str |
181 |
| - authjwt_algorithm: str = 'HS256' |
182 |
| - |
183 |
| - class Config: |
184 |
| - env_file = '.env' |
185 |
| - env_file_encoding = 'utf-8' |
186 |
| - |
187 |
| - |
188 |
| -@AuthJWT.load_env |
189 |
| -def get_settings(): |
190 |
| - return Settings() |
191 |
| - # or you can just parse a list of tuple |
192 |
| - # return [ |
193 |
| - # ("authjwt_access_token_expires",timedelta(minutes=2)), |
194 |
| - # ("authjwt_refresh_token_expires",timedelta(days=5)), |
195 |
| - # ("authjwt_blacklist_enabled","false"), |
196 |
| - # ("authjwt_secret_key","testing"), |
197 |
| - # ("authjwt_algorithm","HS256") |
198 |
| - # ] |
199 |
| - |
200 |
| - |
201 |
| -print(AuthJWT._access_token_expires) |
202 |
| -print(AuthJWT._refresh_token_expires) |
203 |
| -print(AuthJWT._blacklist_enabled) |
204 |
| -print(AuthJWT._secret_key) |
205 |
| -print(AuthJWT._algorithm) |
| 31 | +pip install 'fastapi-jwt-auth[asymmetric]' |
206 | 32 | ```
|
207 | 33 |
|
208 |
| -## Examples |
209 |
| -Examples are available on [examples](/examples) folder. |
210 |
| -There are: |
211 |
| -- [Basic](/examples/basic.py) |
212 |
| -- [Token Optional](/examples/optional_protected_endpoints.py) |
213 |
| -- [Refresh Token](/examples/refresh_tokens.py) |
214 |
| -- [Token Fresh](/examples/token_freshness.py) |
215 |
| -- [Blacklist Token](/examples/blacklist.py) |
216 |
| -- [Blacklist Token Use Redis](/examples/blacklist_redis.py) |
217 |
| - |
218 |
| -Optional: |
219 |
| -- [Use AuthJWT Without Dependency Injection](/examples/without_dependency.py) |
220 |
| -- [On Mutiple Files](/examples/multiple_files) |
221 |
| - |
222 | 34 | ## License
|
223 | 35 | This project is licensed under the terms of the MIT license.
|
0 commit comments