How to handle Authentication & Authorization with Flask and Ariadne (GraphQL)?

406 Views Asked by At

This is the first API I ever make so bare with me.

I was working on a RESTful API made in Flask to interact with my React frontend when I discovered GraphQL. Being an amazing way to save on network recourses I decided to switch to it. I chose Ariadne since there's an easy way to integrate it with Flask.

But while changing all the logic to work with Ariadne I found and issue when authenticating and validating user login. With a REST API I can use the Flask-jwt-extended library to handle user authentication. For example, I have a function for changing the username.

@app.route("/change-username", methods=["POST"]) 
@jwt_required 
def change_username():
     ...
     return {"msg": "Username changed successfully"}, 200 

This endpoint requires the user to be logged in to be accessed. Then I have another to ban a user

@app.route("/ban-user", methods=["POST"]) 
@jwt_required
def ban_user():
     if current_user.role == "moderator":
         ...
        return {"msg": "User has been banned"}, 200
     else:
         return {"msg": "You are not authorized to ban users"}, 401 

This method works since every endpoint can be individually set up to require or not authentication but with GraphQL only one endpoint is used so I either have to make all data publicly available or put all the data behind an authentication wall which is something I don't really want.

Is there any way to individually set up every Query to require or not authentication and how would I handle the currently logged in user this way?

0

There are 0 best solutions below