Course Content
Professional Web API with Flask
Professional Web API with Flask
Permissions
Sometimes we need to differentiate the responsibilities of users on our website. For example, all users may view the list of players, but only registered users can view the list of teams, and only admins can delete, update, or create new instances. In the first and second cases, we simply add or omit the @jwt_required
decorator. The third case will be discussed further.
JWT Claims in Flask
This is referred to as JWT claims in Flask. In JWT, we can pass additional information, such as a flag is_admin=True
. By doing this, we only need to check the user's permissions once when we create the JWT, rather than every time the user makes a request.
Adding Special Claims to JWT
To add a special claim to JWT, we define a function similar to the error handling functions we wrote in the previous chapter:
This function is responsible for granting admin status only to the user with id=1. In this course, we will not cover adding this status to the user table in the database and retrieving this information to add it to the JWT.
Restricting Endpoints Beyond @jwt_required()
To add restrictions to endpoints beyond @jwt_required()
, we include a check for the admin role:
get_jwt()
is also imported from the flask_jwt_extended
library.
In this way, we have a function for adding additional information about the user's status and functionality for checking this status.
Thanks for your feedback!