33
33
'JWT_AUTH_USERNAME_KEY' : 'username' ,
34
34
'JWT_AUTH_PASSWORD_KEY' : 'password' ,
35
35
'JWT_ALGORITHM' : 'HS256' ,
36
+ 'JWT_ROLE' : 'role' ,
36
37
'JWT_LEEWAY' : timedelta (seconds = 10 ),
37
38
'JWT_AUTH_HEADER_PREFIX' : 'JWT' ,
38
39
'JWT_EXPIRATION_DELTA' : timedelta (seconds = 300 ),
@@ -141,7 +142,7 @@ def _default_jwt_error_handler(error):
141
142
])), error .status_code , error .headers
142
143
143
144
144
- def _jwt_required (realm ):
145
+ def _jwt_required (realm , roles ):
145
146
"""Does the actual work of verifying the JWT data in the current request.
146
147
This is done automatically for you by `jwt_required()` but you could call it manually.
147
148
Doing so would be useful in the context of optional JWT access in your APIs.
@@ -163,17 +164,30 @@ def _jwt_required(realm):
163
164
164
165
if identity is None :
165
166
raise JWTError ('Invalid JWT' , 'User does not exist' )
167
+ if roles :
168
+ identity_role = identity .get (current_app .config ['JWT_ROLE' ])
169
+ if not identity_role :
170
+ raise JWTError ('Bad Request' , 'Invalid credentials' )
171
+ if not hasattr (identity_role , "__iter__" ):
172
+ identity_role = [identity_role ]
173
+ if not hasattr (roles , "__iter__" ):
174
+ roles = [roles ]
175
+ if not identity_role or not set (roles ).intersection (identity_role ):
176
+ raise JWTError ('Bad Request' , 'Invalid credentials' )
166
177
167
178
168
- def jwt_required (realm = None ):
179
+
180
+ def jwt_required (realm = None , roles = None ):
169
181
"""View decorator that requires a valid JWT token to be present in the request
170
182
171
183
:param realm: an optional realm
184
+ :param roles: an optional list of roles allowed,
185
+ the role is pick in JWT_ROLE field of identity
172
186
"""
173
187
def wrapper (fn ):
174
188
@wraps (fn )
175
189
def decorator (* args , ** kwargs ):
176
- _jwt_required (realm or current_app .config ['JWT_DEFAULT_REALM' ])
190
+ _jwt_required (realm or current_app .config ['JWT_DEFAULT_REALM' ], roles )
177
191
return fn (* args , ** kwargs )
178
192
return decorator
179
193
return wrapper
0 commit comments