Skip to content

Commit e73eb60

Browse files
committed
JWTIdentity raises common error JWTIdentityError
1 parent 3b63e0d commit e73eb60

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

aiohttp_security/jwt_identity.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,17 @@
1919
AUTH_SCHEME = 'Bearer '
2020

2121

22+
if HAS_JWT:
23+
# This class inherits from ValueError to maintain backward compatibility
24+
# with previous versions of aiohttp-security.
25+
class JWTIdentityError(jwt.exceptions.PyJWTError, ValueError):
26+
pass
27+
28+
else:
29+
class JWTIdentityError(ValueError):
30+
pass
31+
32+
2233
class JWTIdentityPolicy(AbstractIdentityPolicy):
2334
def __init__(self, secret: str, algorithm: str = "HS256", key: str = "login"):
2435
if not HAS_JWT:
@@ -34,14 +45,15 @@ async def identify(self, request: web.Request) -> Optional[str]:
3445
return None
3546

3647
if not header_identity.startswith(AUTH_SCHEME):
37-
raise ValueError("Invalid authorization scheme. "
38-
+ "Should be `{}<token>`".format(AUTH_SCHEME))
48+
raise JWTIdentityError("Invalid authorization scheme. "
49+
+ "Should be `{}<token>`".format(AUTH_SCHEME))
3950

4051
token = header_identity.split(' ')[1].strip()
4152

4253
identity = jwt.decode(token,
4354
self.secret,
4455
algorithms=[self.algorithm])
56+
4557
return identity.get(self.key) # type: ignore[no-any-return]
4658

4759
async def remember(self, request: web.Request, response: web.StreamResponse,

tests/test_jwt_identity.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,3 +80,28 @@ async def check(request):
8080
resp = await client.get('/', headers=headers)
8181
assert 400 == resp.status
8282
assert 'Invalid authorization scheme' in resp.reason
83+
84+
85+
async def test_identify_expired_signature(make_token, aiohttp_client):
86+
kwt_secret_key = "Key" # noqa: S105
87+
88+
token = make_token({'login': 'Andrew', 'exp': 0}, kwt_secret_key)
89+
90+
async def check(request):
91+
policy = request.app[IDENTITY_KEY]
92+
try:
93+
await policy.identify(request)
94+
except jwt.exceptions.PyJWTError as exc:
95+
raise web.HTTPBadRequest(reason=str(exc))
96+
97+
return web.Response()
98+
99+
app = web.Application()
100+
_setup(app, JWTIdentityPolicy(kwt_secret_key), Autz())
101+
app.router.add_route('GET', '/', check)
102+
103+
client = await aiohttp_client(app)
104+
headers = {"Authorization": "Bearer {}".format(token)}
105+
resp = await client.get('/', headers=headers)
106+
assert 400 == resp.status
107+
assert 'Signature has expired' in resp.reason

0 commit comments

Comments
 (0)