Skip to content

Commit aac44e2

Browse files
author
IndominusByte
committed
identity claim -> standard claim 'sub'
1 parent 1c24bc5 commit aac44e2

File tree

7 files changed

+84
-86
lines changed

7 files changed

+84
-86
lines changed

fastapi_jwt_auth/auth_jwt.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ def _get_secret_key(self, algorithm: str, process: str) -> str:
120120

121121
def _create_token(
122122
self,
123-
identity: Union[str,int],
123+
subject: Union[str,int],
124124
type_token: str,
125125
exp_time: Optional[int],
126126
fresh: Optional[bool] = False,
@@ -132,7 +132,7 @@ def _create_token(
132132
"""
133133
Create token for access_token and refresh_token (utf-8)
134134
135-
:param identity: Identifier for who this token is for example id or username from database.
135+
:param subject: Identifier for who this token is for example id or username from database.
136136
:param type_token: indicate token is access_token or refresh_token
137137
:param exp_time: Set the duration of the JWT
138138
:param fresh: Optional when token is access_token this param required
@@ -144,8 +144,8 @@ def _create_token(
144144
:return: Encoded token
145145
"""
146146
# Validation type data
147-
if not isinstance(identity, (str,int)):
148-
raise TypeError("identity must be a string or integer")
147+
if not isinstance(subject, (str,int)):
148+
raise TypeError("subject must be a string or integer")
149149
if not isinstance(fresh, (bool)):
150150
raise TypeError("fresh must be a boolean")
151151
if audience and not isinstance(audience, (str, list, tuple, set, frozenset, GeneratorType)):
@@ -155,15 +155,13 @@ def _create_token(
155155

156156
# Data section
157157
reserved_claims = {
158+
"sub": subject,
158159
"iat": self._get_int_from_datetime(datetime.now(timezone.utc)),
159160
"nbf": self._get_int_from_datetime(datetime.now(timezone.utc)),
160-
"jti": self._get_jwt_identifier(),
161+
"jti": self._get_jwt_identifier()
161162
}
162163

163-
custom_claims = {
164-
"identity": identity,
165-
"type": type_token
166-
}
164+
custom_claims = {"type": type_token}
167165

168166
# for access_token only fresh needed
169167
if type_token == 'access':
@@ -253,7 +251,7 @@ def _get_expired_time(
253251

254252
def create_access_token(
255253
self,
256-
identity: Union[str,int],
254+
subject: Union[str,int],
257255
fresh: Optional[bool] = False,
258256
algorithm: Optional[str] = None,
259257
headers: Optional[Dict] = None,
@@ -267,7 +265,7 @@ def create_access_token(
267265
:return: hash token
268266
"""
269267
return self._create_token(
270-
identity=identity,
268+
subject=subject,
271269
type_token="access",
272270
exp_time=self._get_expired_time("access",expires_time),
273271
fresh=fresh,
@@ -279,7 +277,7 @@ def create_access_token(
279277

280278
def create_refresh_token(
281279
self,
282-
identity: Union[str,int],
280+
subject: Union[str,int],
283281
algorithm: Optional[str] = None,
284282
headers: Optional[Dict] = None,
285283
expires_time: Optional[Union[timedelta,int,bool]] = None,
@@ -292,7 +290,7 @@ def create_refresh_token(
292290
:return: hash token
293291
"""
294292
return self._create_token(
295-
identity=identity,
293+
subject=subject,
296294
type_token="refresh",
297295
exp_time=self._get_expired_time("refresh",expires_time),
298296
algorithm=algorithm,
@@ -634,9 +632,9 @@ def jwt_required(self) -> None:
634632

635633
def jwt_optional(self) -> None:
636634
"""
637-
If an access token in present in the request you can get data from get_raw_jwt() or get_jwt_identity(),
635+
If an access token in present in the request you can get data from get_raw_jwt() or get_jwt_subject(),
638636
If no access token is present in the request, this endpoint will still be called, but
639-
get_raw_jwt() or get_jwt_identity() will return None
637+
get_raw_jwt() or get_jwt_subject() will return None
640638
"""
641639
if len(self._token_location) == 2:
642640
if self._token and self.jwt_in_headers:
@@ -698,15 +696,15 @@ def get_jti(self,encoded_token: str) -> str:
698696
"""
699697
return self._verified_token(encoded_token)['jti']
700698

701-
def get_jwt_identity(self) -> Optional[Union[str,int]]:
699+
def get_jwt_subject(self) -> Optional[Union[str,int]]:
702700
"""
703-
this will return the identity of the JWT that is accessing this endpoint.
701+
this will return the subject of the JWT that is accessing this endpoint.
704702
If no JWT is present, `None` is returned instead.
705703
706-
:return: identity of JWT
704+
:return: sub of JWT
707705
"""
708706
if self._token:
709-
return self._verified_token(self._token)['identity']
707+
return self._verified_token(self._token)['sub']
710708
return None
711709

712710
def get_unverified_jwt_headers(self,encoded_token: Optional[str] = None) -> dict:

tests/test_config.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -71,20 +71,20 @@ class TokenFalse(BaseSettings):
7171
def get_expired_false():
7272
return TokenFalse()
7373

74-
access_token = Authorize.create_access_token(identity=1)
74+
access_token = Authorize.create_access_token(subject=1)
7575
assert 'exp' not in jwt.decode(access_token,"testing",algorithms="HS256")
7676

77-
refresh_token = Authorize.create_refresh_token(identity=1)
77+
refresh_token = Authorize.create_refresh_token(subject=1)
7878
assert 'exp' not in jwt.decode(refresh_token,"testing",algorithms="HS256")
7979

8080
def test_secret_key_not_exist(client,Authorize):
8181
AuthJWT._secret_key = None
8282

8383
with pytest.raises(RuntimeError,match=r"AUTHJWT_SECRET_KEY"):
84-
Authorize.create_access_token(identity='test')
84+
Authorize.create_access_token(subject='test')
8585

8686
Authorize._secret_key = "secret"
87-
token = Authorize.create_access_token(identity=1)
87+
token = Authorize.create_access_token(subject=1)
8888
Authorize._secret_key = None
8989

9090
with pytest.raises(RuntimeError,match=r"AUTHJWT_SECRET_KEY"):
@@ -103,7 +103,7 @@ def get_settings_one():
103103

104104
Authorize = AuthJWT()
105105

106-
token = Authorize.create_access_token(identity='test')
106+
token = Authorize.create_access_token(subject='test')
107107

108108
response = client.get('/protected',headers={"Authorization": f"Bearer {token}"})
109109
assert response.status_code == 200

tests/test_create_token.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -16,80 +16,80 @@ def get_settings():
1616
with pytest.raises(TypeError,match=r"missing 1 required positional argument"):
1717
Authorize.create_access_token()
1818

19-
with pytest.raises(TypeError,match=r"identity"):
20-
Authorize.create_access_token(identity=0.123)
19+
with pytest.raises(TypeError,match=r"subject"):
20+
Authorize.create_access_token(subject=0.123)
2121

2222
with pytest.raises(TypeError,match=r"fresh"):
23-
Authorize.create_access_token(identity="test",fresh="lol")
23+
Authorize.create_access_token(subject="test",fresh="lol")
2424

2525
with pytest.raises(ValueError,match=r"dictionary update sequence element"):
26-
Authorize.create_access_token(identity=1,headers="test")
26+
Authorize.create_access_token(subject=1,headers="test")
2727

2828
def test_create_refresh_token(Authorize):
2929
with pytest.raises(TypeError,match=r"missing 1 required positional argument"):
3030
Authorize.create_refresh_token()
3131

32-
with pytest.raises(TypeError,match=r"identity"):
33-
Authorize.create_refresh_token(identity=0.123)
32+
with pytest.raises(TypeError,match=r"subject"):
33+
Authorize.create_refresh_token(subject=0.123)
3434

3535
with pytest.raises(ValueError,match=r"dictionary update sequence element"):
36-
Authorize.create_refresh_token(identity=1,headers="test")
36+
Authorize.create_refresh_token(subject=1,headers="test")
3737

3838
def test_create_dynamic_access_token_expires(Authorize):
3939
expires_time = int(datetime.now(timezone.utc).timestamp()) + 90
40-
token = Authorize.create_access_token(identity=1,expires_time=90)
40+
token = Authorize.create_access_token(subject=1,expires_time=90)
4141
assert jwt.decode(token,"testing",algorithms="HS256")['exp'] == expires_time
4242

4343
expires_time = int(datetime.now(timezone.utc).timestamp()) + 86400
44-
token = Authorize.create_access_token(identity=1,expires_time=timedelta(days=1))
44+
token = Authorize.create_access_token(subject=1,expires_time=timedelta(days=1))
4545
assert jwt.decode(token,"testing",algorithms="HS256")['exp'] == expires_time
4646

4747
expires_time = int(datetime.now(timezone.utc).timestamp()) + 2
48-
token = Authorize.create_access_token(identity=1,expires_time=True)
48+
token = Authorize.create_access_token(subject=1,expires_time=True)
4949
assert jwt.decode(token,"testing",algorithms="HS256")['exp'] == expires_time
5050

51-
token = Authorize.create_access_token(identity=1,expires_time=False)
51+
token = Authorize.create_access_token(subject=1,expires_time=False)
5252
assert 'exp' not in jwt.decode(token,"testing",algorithms="HS256")
5353

5454
with pytest.raises(TypeError,match=r"expires_time"):
55-
Authorize.create_access_token(identity=1,expires_time="test")
55+
Authorize.create_access_token(subject=1,expires_time="test")
5656

5757
def test_create_dynamic_refresh_token_expires(Authorize):
5858
expires_time = int(datetime.now(timezone.utc).timestamp()) + 90
59-
token = Authorize.create_refresh_token(identity=1,expires_time=90)
59+
token = Authorize.create_refresh_token(subject=1,expires_time=90)
6060
assert jwt.decode(token,"testing",algorithms="HS256")['exp'] == expires_time
6161

6262
expires_time = int(datetime.now(timezone.utc).timestamp()) + 86400
63-
token = Authorize.create_refresh_token(identity=1,expires_time=timedelta(days=1))
63+
token = Authorize.create_refresh_token(subject=1,expires_time=timedelta(days=1))
6464
assert jwt.decode(token,"testing",algorithms="HS256")['exp'] == expires_time
6565

6666
expires_time = int(datetime.now(timezone.utc).timestamp()) + 4
67-
token = Authorize.create_refresh_token(identity=1,expires_time=True)
67+
token = Authorize.create_refresh_token(subject=1,expires_time=True)
6868
assert jwt.decode(token,"testing",algorithms="HS256")['exp'] == expires_time
6969

70-
token = Authorize.create_refresh_token(identity=1,expires_time=False)
70+
token = Authorize.create_refresh_token(subject=1,expires_time=False)
7171
assert 'exp' not in jwt.decode(token,"testing",algorithms="HS256")
7272

7373
with pytest.raises(TypeError,match=r"expires_time"):
74-
Authorize.create_refresh_token(identity=1,expires_time="test")
74+
Authorize.create_refresh_token(subject=1,expires_time="test")
7575

7676
def test_create_token_invalid_type_data_audience(Authorize):
7777
with pytest.raises(TypeError,match=r"audience"):
78-
Authorize.create_access_token(identity=1,audience=1)
78+
Authorize.create_access_token(subject=1,audience=1)
7979

8080
with pytest.raises(TypeError,match=r"audience"):
81-
Authorize.create_refresh_token(identity=1,audience=1)
81+
Authorize.create_refresh_token(subject=1,audience=1)
8282

8383
def test_create_token_invalid_algorithm(Authorize):
8484
with pytest.raises(ValueError,match=r"Algorithm"):
85-
Authorize.create_access_token(identity=1,algorithm="test")
85+
Authorize.create_access_token(subject=1,algorithm="test")
8686

8787
with pytest.raises(ValueError,match=r"Algorithm"):
88-
Authorize.create_refresh_token(identity=1,algorithm="test")
88+
Authorize.create_refresh_token(subject=1,algorithm="test")
8989

9090
def test_create_token_invalid_type_data_algorithm(Authorize):
9191
with pytest.raises(TypeError,match=r"algorithm"):
92-
Authorize.create_access_token(identity=1,algorithm=1)
92+
Authorize.create_access_token(subject=1,algorithm=1)
9393

9494
with pytest.raises(TypeError,match=r"algorithm"):
95-
Authorize.create_refresh_token(identity=1,algorithm=1)
95+
Authorize.create_refresh_token(subject=1,algorithm=1)

0 commit comments

Comments
 (0)