JWTIdentityPolicy polishing (#161)

* Polishing JWT policy

* Simplify tests

* Minor cleaning
This commit is contained in:
Oleh Kuchuk
2018-05-21 22:07:14 +03:00
committed by Andrew Svetlov
parent ff2171d6c5
commit 42769df454
2 changed files with 65 additions and 28 deletions

View File

@@ -3,6 +3,7 @@
"""
from .abc import AbstractIdentityPolicy
try:
import jwt
except ImportError: # pragma: no cover
@@ -10,22 +11,32 @@ except ImportError: # pragma: no cover
AUTH_HEADER_NAME = 'Authorization'
AUTH_SCHEME = 'Bearer '
class JWTIdentityPolicy(AbstractIdentityPolicy):
def __init__(self, secret, algorithm=None):
def __init__(self, secret, algorithm='HS256'):
if jwt is None:
raise RuntimeError("Please install pyjwt")
raise RuntimeError('Please install `PyJWT`')
self.secret = secret
self.algorithm = 'HS256' if algorithm is None else algorithm
self.algorithm = algorithm
async def identify(self, request):
header_identity = request.headers.get(AUTH_HEADER_NAME)
identity = jwt.decode(header_identity,
if header_identity is None:
return
if not header_identity.startswith(AUTH_SCHEME):
raise ValueError('Invalid authorization scheme. ' +
'Should be `Bearer <token>`')
token = header_identity.split(' ')[1].strip()
identity = jwt.decode(token,
self.secret,
algorithm=self.algorithm)
return identity['identity']
return identity
async def remember(self, *args, **kwargs): # pragma: no cover
pass