aiohttp-security/aiohttp_security/jwt_identity.py

52 lines
1.4 KiB
Python
Raw Normal View History

2018-04-25 20:52:36 +00:00
"""Identity policy for storing info in the jwt token.
"""
2020-12-18 17:58:38 +00:00
from typing import Optional
from aiohttp import web
2018-04-25 20:52:36 +00:00
from .abc import AbstractIdentityPolicy
2018-04-25 20:52:36 +00:00
try:
import jwt
2020-12-18 17:58:38 +00:00
HAS_JWT = True
2018-04-25 20:52:36 +00:00
except ImportError: # pragma: no cover
2020-12-18 17:58:38 +00:00
HAS_JWT = False
2018-04-25 20:52:36 +00:00
AUTH_HEADER_NAME = 'Authorization'
AUTH_SCHEME = 'Bearer '
2018-04-25 20:52:36 +00:00
class JWTIdentityPolicy(AbstractIdentityPolicy):
2020-12-18 17:58:38 +00:00
def __init__(self, secret: str, algorithm: str = 'HS256'):
if not HAS_JWT:
raise RuntimeError('Please install `PyJWT`')
2018-04-25 20:52:36 +00:00
self.secret = secret
self.algorithm = algorithm
2018-04-25 20:52:36 +00:00
2020-12-18 17:58:38 +00:00
async def identify(self, request: web.Request) -> Optional[str]:
2018-04-25 20:52:36 +00:00
header_identity = request.headers.get(AUTH_HEADER_NAME)
if header_identity is None:
2020-12-18 17:58:38 +00:00
return None
if not header_identity.startswith(AUTH_SCHEME):
raise ValueError('Invalid authorization scheme. ' +
2020-12-18 17:58:38 +00:00
'Should be `{}<token>`'.format(AUTH_SCHEME))
token = header_identity.split(' ')[1].strip()
identity = jwt.decode(token,
2018-04-25 20:52:36 +00:00
self.secret,
2018-09-06 10:06:55 +00:00
algorithms=[self.algorithm])
return identity
2018-04-25 20:52:36 +00:00
2020-12-18 17:58:38 +00:00
async def remember(self, request: web.Request, response: web.StreamResponse,
identity: str, **kwargs: None) -> None:
2018-04-25 20:52:36 +00:00
pass
2020-12-18 17:58:38 +00:00
async def forget(self, request: web.Request, response: web.StreamResponse) -> None:
2018-04-25 20:52:36 +00:00
pass