Skip to content

Commit 6e7015d

Browse files
feat: Regional twr header in the access token (#546)
Co-authored-by: Elise Shanholtz <eshanholtz@twilio.com>
1 parent 94294e1 commit 6e7015d

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

tests/unit/jwt/test_access_token.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,18 @@ def test_empty_grants(self):
5454
self._validate_claims(decoded_token.payload)
5555
assert_equal({}, decoded_token.payload['grants'])
5656

57+
def test_region(self):
58+
scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret', region='foo')
59+
token = scat.to_jwt()
60+
decoded_token = AccessToken.from_jwt(token, 'secret')
61+
assert_equal(decoded_token.headers['twr'], 'foo')
62+
63+
def test_empty_region(self):
64+
scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
65+
token = scat.to_jwt()
66+
decoded_token = AccessToken.from_jwt(token, 'secret')
67+
self.assertRaises(KeyError, lambda: decoded_token.headers['twr'])
68+
5769
def test_nbf(self):
5870
now = int(time.mktime(datetime.now().timetuple()))
5971
scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret', nbf=now)

twilio/jwt/access_token/__init__.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,15 @@ def __str__(self):
2121
class AccessToken(Jwt):
2222
"""Access Token containing one or more AccessTokenGrants used to access Twilio Resources"""
2323
def __init__(self, account_sid, signing_key_sid, secret, grants=None,
24-
identity=None, nbf=Jwt.GENERATE, ttl=3600, valid_until=None):
24+
identity=None, nbf=Jwt.GENERATE, ttl=3600, valid_until=None, region=None):
2525
grants = grants or []
2626
if any(not isinstance(g, AccessTokenGrant) for g in grants):
2727
raise ValueError('Grants must be instances of AccessTokenGrant.')
2828

2929
self.account_sid = account_sid
3030
self.signing_key_sid = signing_key_sid
3131
self.identity = identity
32+
self.region = region
3233
self.grants = grants
3334
super(AccessToken, self).__init__(
3435
secret_key=secret,
@@ -47,9 +48,12 @@ def add_grant(self, grant):
4748
self.grants.append(grant)
4849

4950
def _generate_headers(self):
50-
return {
51+
headers = {
5152
'cty': 'twilio-fpa;v=1'
5253
}
54+
if self.region and isinstance(self.region, str):
55+
headers['twr'] = self.region
56+
return headers
5357

5458
def _generate_payload(self):
5559
now = int(time.time())

0 commit comments

Comments
 (0)