You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: README.md
+169-46
Original file line number
Diff line number
Diff line change
@@ -8,58 +8,98 @@
8
8
[](https://github.com/feteu/asgi-claim-validator/actions/workflows/publish-pypi.yaml)
9
9
[](https://github.com/feteu/asgi-claim-validator/actions/workflows/test.yaml)
10
10
11
-
# asgi-claim-validator
11
+
# asgi-claim-validator 🚀
12
12
13
13
A focused ASGI middleware for validating additional claims within JWT tokens to enhance token-based workflows.
14
14
15
-
## Overview
15
+
> **Note:** If you find this project useful, please consider giving it a star ⭐ on GitHub. This helps prioritize its maintenance and development. If you encounter any typos, bugs 🐛, or have new feature requests, feel free to open an issue. I will be happy to address them.
16
+
17
+
18
+
## Table of Contents 📑
19
+
20
+
1.[Overview 📖](#overview-)
21
+
1.[Purpose 🎯](#purpose-)
22
+
2.[Key Features ✨](#key-features-)
23
+
3.[Use Cases 💡](#use-cases-)
24
+
4.[Compatibility 🤝](#compatibility-)
25
+
2.[Installation 🛠️](#installation-)
26
+
3.[Usage 📚](#usage-)
27
+
1.[Basic Usage 🌟](#basic-usage)
28
+
2.[Configuration ⚙️](#configuration-)
29
+
3.[Error Handlers 🚨](#error-handlers-)
30
+
4.[Examples 📝](#examples-)
31
+
5.[Testing 🧪](#testing-)
32
+
6.[Contributing 🤝](#contributing-)
33
+
7.[License 📜](#license-)
34
+
35
+
36
+
## Overview 📖
16
37
17
38
`asgi-claim-validator` is an ASGI middleware designed to validate additional claims within JWT tokens. Built in addition to the default JWT verification implementation of Connexion, it enhances token-based workflows by ensuring that specific claims are present and meet certain criteria before allowing access to protected endpoints. This middleware allows consumers to validate claims on an endpoint/method level and is compatible with popular ASGI frameworks such as Starlette, FastAPI, and Connexion.
18
39
19
-
## Features
40
+
### Purpose 🎯
41
+
42
+
The primary purpose of `asgi-claim-validator` is to provide an additional layer of security by validating specific claims within JWT tokens. This ensures that only requests with valid and authorized tokens can access protected resources. The middleware is highly configurable, allowing developers to define essential claims, allowed values, and whether blank values are permitted. It also supports path and method filtering, enabling claim validation to be applied selectively based on the request path and HTTP method.
43
+
44
+
### Key Features ✨
20
45
21
46
-**Claim Validation**: Validate specific claims within JWT tokens, such as `sub`, `iss`, `aud`, `exp`, `iat`, and `nbf`.
22
47
-**Customizable Claims**: Define essential claims, allowed values, and whether blank values are permitted.
23
48
-**Path and Method Filtering**: Apply claim validation to specific paths and HTTP methods.
24
49
-**Exception Handling**: Integrate with custom exception handlers to provide meaningful error responses.
25
50
-**Logging**: Log validation errors for debugging and monitoring purposes.
51
+
-**Flexible Configuration**: Easily configure the middleware using a variety of options to suit different use cases.
52
+
-**Middleware Positioning**: Integrate the middleware at different positions within the ASGI application stack.
53
+
-**Token Extraction**: Extract tokens from various parts of the request, such as headers, cookies, or query parameters.
54
+
-**Custom Claim Validators**: Implement custom claim validation logic by providing your own validation functions.
55
+
-**Support for Multiple Frameworks**: Compatible with popular ASGI frameworks such as Starlette, FastAPI, and Connexion.
56
+
-**Performance Optimization**: Efficiently handle claim validation with minimal impact on request processing time.
57
+
-**Extensive Test Coverage**: Comprehensive test suite to ensure reliability and correctness of the middleware.
58
+
59
+
### Use Cases 💡
26
60
27
-
## Installation
61
+
-**API Security**: Enhance the security of your API by ensuring that only requests with valid JWT tokens and specific claims can access protected endpoints.
62
+
-**Role-Based Access Control**: Implement role-based access control by validating claims that represent user roles and permissions.
63
+
-**Compliance**: Ensure compliance with security policies by enforcing the presence and validity of specific claims within JWT tokens.
64
+
-**Custom Authentication Logic**: Implement custom authentication logic by providing your own claim validation functions.
28
65
29
-
Install the package using pip:
66
+
### Compatibility 🤝
67
+
68
+
`asgi-claim-validator` is compatible with popular ASGI frameworks such as Starlette, FastAPI, and Connexion. It can be easily integrated into existing ASGI applications and configured to suit various use cases and requirements.
69
+
70
+
By using `asgi-claim-validator`, you can enhance the security and flexibility of your token-based authentication workflows, ensuring that only authorized requests can access your protected resources.
71
+
72
+
73
+
## Installation 🛠️
74
+
75
+
To install the `asgi-claim-validator` package, use the following pip command:
30
76
31
77
```sh
32
78
pip install asgi-claim-validator
33
79
```
34
80
35
-
## Usage
36
81
37
-
### Basic Usage
82
+
##Usage 📚
38
83
39
-
Here's an example of how to use `asgi-claim-validator` with Starlette:
84
+
### Basic Usage 🌟
40
85
41
-
```python
42
-
from starlette.applications import Starlette
43
-
from starlette.requests import Request
44
-
from starlette.responses import JSONResponse
45
-
from starlette.routing import Route
46
-
from asgi_claim_validator import ClaimValidatorMiddleware
86
+
Below is an example of how to integrate `ClaimValidatorMiddleware` with a Connexion application. This middleware validates specific claims within JWT tokens for certain endpoints.
The `ClaimValidatorMiddleware` requires several parameters to function correctly. The `claims_callable` parameter is a callable that extracts token information from the Connexion context. This parameter must be specified and is typically dependent on the framework being used. The `secured` parameter is a dictionary that defines the secured paths and the claims that need to be validated. For instance, in the provided example, the `/secured` path requires the `sub` claim to be `admin` and the `iss` claim to be `https://example.com` for GET requests. The `skipped` parameter is a dictionary that specifies the paths and methods that should be excluded from validation. In the example, the `/skipped` path is skipped for GET requests.
89
+
90
+
```python
91
+
from asgi_claim_validator.middleware import ClaimValidatorMiddleware
The `ClaimValidatorMiddleware` requires two main configuration pieces: `secured` and `skipped`. These configurations are validated using JSON schemas to ensure correctness.
127
+
128
+
> **Note:** The path regex patterns provided in the `secured` and `skipped` parameters will be automatically escaped by the middleware.
129
+
130
+
#### Secured Configuration
131
+
132
+
The `secured` configuration is a dictionary that defines the paths and the claims that need to be validated. Each path is associated with a dictionary of HTTP methods, and each method is associated with a dictionary of claims. Each claim can have the following properties:
133
+
-`essential`: A boolean indicating whether the claim is essential.
134
+
-`allow_blank`: A boolean indicating whether blank values are allowed.
135
+
-`values`: A list of allowed values for the claim.
136
+
137
+
Example:
138
+
```python
139
+
secured={
140
+
"^/secured/?$": {
141
+
"GET": {
142
+
"sub": {
143
+
"essential": True,
144
+
"allow_blank": False,
145
+
"values": ["admin"],
146
+
},
147
+
"iss": {
148
+
"essential": True,
149
+
"allow_blank": False,
150
+
"values": ["https://example.com"],
151
+
},
152
+
},
153
+
},
154
+
}
155
+
```
156
+
157
+
#### Skipped Configuration
158
+
159
+
The `skipped` configuration is a dictionary that defines the paths and methods that should be excluded from validation. Each path is associated with a list of HTTP methods.
83
160
84
-
Integrate `asgi-claim-validator` with custom exception handlers to provide meaningful error responses. Below are examples for Starlette and Connexion. Refer to the specific framework examples in the [examples](examples) directory for detailed implementation.
161
+
Example:
162
+
```python
163
+
skipped={
164
+
"^/skipped/?$": ["GET"],
165
+
}
166
+
```
85
167
86
-
###Middleware Configuration
168
+
#### JSON Schema Validation
87
169
88
-
Configure the middleware with the following options:
170
+
Both `secured` and `skipped` configurations are validated using JSON schemas to ensure their correctness. This validation helps catch configuration errors early and ensures that the middleware behaves as expected.
89
171
90
-
-**claims_callable**: A callable that returns the JWT claims to be validated.
91
-
-**secured**: A dictionary defining the paths and methods that require claim validation.
92
-
-**skipped**: A dictionary defining the paths and methods to be excluded from claim validation.
93
-
-**raise_on_unspecified_path**: Raise an exception if the path is not specified in the `secured` or `skipped` dictionaries.
94
-
-**raise_on_unspecified_method**: Raise an exception if the method is not specified for a secured path.
95
172
96
-
### Claim Validation Options
173
+
### Error Handlers 🚨
97
174
98
-
Configure claims with the following options:
175
+
To handle exceptions raised by this middleware, you can configure your framework (such as Starlette or Connexion) to catch and process them dynamically. For security reasons, the exception messages are kept generic, but you can customize them using the exception parameters.
99
176
100
-
-**essential**: Indicates if the claim is essential (default: `False`).
101
-
-**allow_blank**: Indicates if blank values are allowed (default: `True`).
102
-
-**values**: A list of allowed values for the claim.
177
+
#### Connexion
178
+
179
+
```python
180
+
from asgi_claim_validator import ClaimValidatorMiddleware, ClaimValidatorException
181
+
from connexion import AsyncApp
182
+
from connexion.lifecycle import ConnexionRequest, ConnexionResponse
Refer to the [app.py](examples/starlette/simple/app.py) file for a complete example using Starlette.
220
+
To see a complete example using Starlette, refer to the [app.py](examples/starlette/simple/app.py) file.
108
221
109
222
### Connexion Example
110
-
Refer to the [app.py](examples/connexion/simple/app.py) file for a complete example using Connexion.
223
+
Check out the [app.py](examples/connexion/simple/app.py) file for a simple example using Connexion. For a comprehensive example that demonstrates automatic extraction and validation of token claims with Connexion, see the [app.py](examples/connexion/complex/app.py) file.
111
224
112
-
## Testing
225
+
## Testing 🧪
113
226
Run the tests using `pytest`:
114
227
115
228
```sh
116
229
poetry run pytest
117
230
```
118
231
119
-
## Contributing
232
+
### Scope:
233
+
234
+
-**Middleware Functionality**: Ensures correct validation of JWT claims and proper handling of secured and skipped paths.
235
+
-**Exception Handling**: Verifies that custom exceptions are raised and handled appropriately.
236
+
-**Configuration Validation**: Checks the correctness of middleware configuration for secured and skipped paths.
237
+
-**Integration with Frameworks**: Confirms seamless integration with ASGI frameworks like Starlette and Connexion.
238
+
-**Custom Claim Validators**: Tests the implementation and usage of custom claim validation logic.
239
+
240
+
241
+
## Contributing 🤝
120
242
Contributions are welcome! Please refer to the [CONTRIBUTING.md](CONTRIBUTING.md) file for guidelines on how to contribute to this project.
121
243
122
-
## License
244
+
245
+
## License 📜
123
246
This project is licensed under the GNU GPLv3 License. See the [LICENSE](LICENSE) file for more details.
0 commit comments