2018-04-25 20:52:36 +00:00
|
|
|
"""Identity policy for storing info in the jwt token.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
from .abc import AbstractIdentityPolicy
|
2018-05-21 19:07:14 +00:00
|
|
|
|
2018-04-25 20:52:36 +00:00
|
|
|
try:
|
|
|
|
import jwt
|
|
|
|
except ImportError: # pragma: no cover
|
|
|
|
jwt = None
|
|
|
|
|
|
|
|
|
|
|
|
AUTH_HEADER_NAME = 'Authorization'
|
2018-05-21 19:07:14 +00:00
|
|
|
AUTH_SCHEME = 'Bearer '
|
2018-04-25 20:52:36 +00:00
|
|
|
|
|
|
|
|
|
|
|
class JWTIdentityPolicy(AbstractIdentityPolicy):
|
2018-05-21 19:07:14 +00:00
|
|
|
def __init__(self, secret, algorithm='HS256'):
|
2018-04-25 20:52:36 +00:00
|
|
|
if jwt is None:
|
2018-05-21 19:07:14 +00:00
|
|
|
raise RuntimeError('Please install `PyJWT`')
|
2018-04-25 20:52:36 +00:00
|
|
|
self.secret = secret
|
2018-05-21 19:07:14 +00:00
|
|
|
self.algorithm = algorithm
|
2018-04-25 20:52:36 +00:00
|
|
|
|
|
|
|
async def identify(self, request):
|
|
|
|
header_identity = request.headers.get(AUTH_HEADER_NAME)
|
2018-05-21 19:07:14 +00:00
|
|
|
|
|
|
|
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,
|
2018-04-25 20:52:36 +00:00
|
|
|
self.secret,
|
|
|
|
algorithm=self.algorithm)
|
2018-05-21 19:07:14 +00:00
|
|
|
return identity
|
2018-04-25 20:52:36 +00:00
|
|
|
|
|
|
|
async def remember(self, *args, **kwargs): # pragma: no cover
|
|
|
|
pass
|
|
|
|
|
|
|
|
async def forget(self, request, response): # pragma: no cover
|
|
|
|
pass
|