Skip to content

feat: Regional twr header in the access token #546

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 23, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions tests/unit/jwt/test_access_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,18 @@ def test_empty_grants(self):
self._validate_claims(decoded_token.payload)
assert_equal({}, decoded_token.payload['grants'])

def test_region(self):
scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret', region='foo')
token = scat.to_jwt()
decoded_token = AccessToken.from_jwt(token, 'secret')
assert_equal(decoded_token.headers['twr'], 'foo')

def test_empty_region(self):
scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret')
token = scat.to_jwt()
decoded_token = AccessToken.from_jwt(token, 'secret')
self.assertRaises(KeyError, lambda: decoded_token.headers['twr'])

def test_nbf(self):
now = int(time.mktime(datetime.now().timetuple()))
scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret', nbf=now)
Expand Down
8 changes: 6 additions & 2 deletions twilio/jwt/access_token/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,15 @@ def __str__(self):
class AccessToken(Jwt):
"""Access Token containing one or more AccessTokenGrants used to access Twilio Resources"""
def __init__(self, account_sid, signing_key_sid, secret, grants=None,
identity=None, nbf=Jwt.GENERATE, ttl=3600, valid_until=None):
identity=None, nbf=Jwt.GENERATE, ttl=3600, valid_until=None, region=None):
grants = grants or []
if any(not isinstance(g, AccessTokenGrant) for g in grants):
raise ValueError('Grants must be instances of AccessTokenGrant.')

self.account_sid = account_sid
self.signing_key_sid = signing_key_sid
self.identity = identity
self.region = region
self.grants = grants
super(AccessToken, self).__init__(
secret_key=secret,
Expand All @@ -47,9 +48,12 @@ def add_grant(self, grant):
self.grants.append(grant)

def _generate_headers(self):
return {
headers = {
'cty': 'twilio-fpa;v=1'
}
if self.region and isinstance(self.region, str):
headers['twr'] = self.region
return headers

def _generate_payload(self):
now = int(time.time())
Expand Down