chore: import upstream snapshot with attribution
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
# Run sample
|
||||
|
||||
## Set up environment
|
||||
|
||||
```sh
|
||||
python -m venv
|
||||
source ./venv/bin/activate
|
||||
```
|
||||
|
||||
## Install dependencies
|
||||
|
||||
```sh
|
||||
pip install PyJWT
|
||||
```
|
||||
|
||||
## Run code
|
||||
|
||||
```sh
|
||||
python lab.py
|
||||
```
|
||||
|
||||
You should see output similar to:
|
||||
|
||||
```text
|
||||
Encoded JWT: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlVzZXIgVXNlcnNvbiIsImFkbWluIjp0cnVlLCJpYXQiOjE3NTkxNjgzMDEsImV4cCI6MTc1OTE3MTkwMX0.tz0UYNNtGVC61DWjVDF8xlhpNkp5XBtxmQH3m_RNwe8
|
||||
✅ Token is valid.
|
||||
Decoded claims:
|
||||
sub: 1234567890
|
||||
name: User Userson
|
||||
admin: True
|
||||
iat: 1759168301
|
||||
exp: 1759171901
|
||||
```
|
||||
@@ -0,0 +1,41 @@
|
||||
# pip install PyJWT
|
||||
|
||||
# create a token
|
||||
import jwt
|
||||
from jwt.exceptions import ExpiredSignatureError, InvalidTokenError
|
||||
import datetime
|
||||
|
||||
# Secret key used to sign the JWT
|
||||
secret_key = 'your-secret-key'
|
||||
|
||||
header = {
|
||||
"alg": "HS256",
|
||||
"typ": "JWT"
|
||||
}
|
||||
|
||||
# the user info andits claims and expiry time
|
||||
payload = {
|
||||
"sub": "1234567890", # Subject (user ID)
|
||||
"name": "User Userson", # Custom claim
|
||||
"admin": True, # Custom claim
|
||||
"iat": datetime.datetime.utcnow(),# Issued at
|
||||
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1) # Expiry
|
||||
}
|
||||
|
||||
# encode it
|
||||
encoded_jwt = jwt.encode(payload, secret_key, algorithm="HS256", headers=header)
|
||||
|
||||
print("Encoded JWT:", encoded_jwt)
|
||||
|
||||
# validate a token
|
||||
try:
|
||||
decoded = jwt.decode(encoded_jwt, secret_key, algorithms=["HS256"])
|
||||
print("✅ Token is valid.")
|
||||
print("Decoded claims:")
|
||||
for key, value in decoded.items():
|
||||
print(f" {key}: {value}")
|
||||
except ExpiredSignatureError:
|
||||
print("❌ Token has expired.")
|
||||
except InvalidTokenError as e:
|
||||
print(f"❌ Invalid token: {e}")
|
||||
|
||||
Reference in New Issue
Block a user