3333 'JWT_AUTH_USERNAME_KEY' : 'username' ,
3434 'JWT_AUTH_PASSWORD_KEY' : 'password' ,
3535 'JWT_ALGORITHM' : 'HS256' ,
36+ 'JWT_ROLE' : 'role' ,
3637 'JWT_LEEWAY' : timedelta (seconds = 10 ),
3738 'JWT_AUTH_HEADER_PREFIX' : 'JWT' ,
3839 'JWT_EXPIRATION_DELTA' : timedelta (seconds = 300 ),
@@ -141,7 +142,7 @@ def _default_jwt_error_handler(error):
141142 ])), error .status_code , error .headers
142143
143144
144- def _jwt_required (realm ):
145+ def _jwt_required (realm , roles ):
145146 """Does the actual work of verifying the JWT data in the current request.
146147 This is done automatically for you by `jwt_required()` but you could call it manually.
147148 Doing so would be useful in the context of optional JWT access in your APIs.
@@ -163,17 +164,30 @@ def _jwt_required(realm):
163164
164165 if identity is None :
165166 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' )
166177
167178
168- def jwt_required (realm = None ):
179+
180+ def jwt_required (realm = None , roles = None ):
169181 """View decorator that requires a valid JWT token to be present in the request
170182
171183 :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
172186 """
173187 def wrapper (fn ):
174188 @wraps (fn )
175189 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 )
177191 return fn (* args , ** kwargs )
178192 return decorator
179193 return wrapper
0 commit comments