More test cases for request signing and added helpers to verify signature

This commit is contained in:
Eliot Berriot 2018-03-24 16:24:10 +01:00
parent aa7365b71f
commit 4522f5997e
No known key found for this signature in database
GPG key ID: DD6965E2476E5C27
2 changed files with 127 additions and 8 deletions

View file

@ -1,3 +1,6 @@
import requests
import requests_http_signature
from cryptography.hazmat.primitives import serialization as crypto_serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend as crypto_default_backend
@ -19,3 +22,35 @@ def get_key_pair(size=2048):
)
return private_key, public_key
def verify(request, public_key):
return requests_http_signature.HTTPSignatureAuth.verify(
request,
key_resolver=lambda **kwargs: public_key
)
def verify_django(django_request, public_key):
"""
Given a django WSGI request, create an underlying requests.PreparedRequest
instance we can verify
"""
headers = django_request.META.get('headers', {}).copy()
for h, v in list(headers.items()):
# we include lower-cased version of the headers for compatibility
# with requests_http_signature
headers[h.lower()] = v
try:
signature = headers['authorization']
except KeyError:
raise exceptions.MissingSignature
request = requests.Request(
method=django_request.method,
url='http://noop',
data=django_request.body,
headers=headers)
prepared_request = request.prepare()
return verify(request, public_key)