Flask GraphQL JWT Authentication
By: Ashish Ansurkar
Tags: Authentication, Flask, GraphQL, Python, Jwt

Image by Fabio Grandis from Pixabay

Authentication is the first thing we need when we put our GraphQL — Flask app open for the clients. And it’s not that hard to configure the secure platform. This article will guide you through a few simple steps to configure JWT (JSON Web Token) authentication for GraphQL developed on the Flask web framework. Here is the link if you want to know more about JWT (https://en.wikipedia.org/wiki/JSON_Web_Token). So, let’s get started…

Please keep in mind that this article is specifically for GraphQL authentication so I haven’t put much weight on the basic setup. If you are just starting with this concept then this (https://medium.com/python-in-plain-english/getting-started-with-graphql-and-flask-13a99513e764)article might help you before you go ahead.

Installations:

$ pip install Flask Flask-GraphQL Flask-GraphQL-Auth SQLAlchemy graphene graphene-sqlalchemy

Let’s import the packages:

Let’s create a simple SQLite database and create a base from a declarative concept of Sqlalchemy and let’s also add the code for the basic start-up of our flask app:

Models:

Here we will configure two models — one for a user and one for stores belong to that user.

Now let’s create the tables into our database as per our models’ configurations (add below line to the code):

Base.metadata.create_all(engine)

Let’s create UserObject and StoreObject for the GraphQL:

Now, let’s create our first user and query it:

Create User mutation:

2. Create a query class for the User object:

3. Define Query and Mutation classes into the schema and add to the GraphQLView:

Let’s check if it’s working !!

http://127.0.0.1:5000/graphql

Create a new user

Retrieve all users

Authentication:

Now let’s start with the authentication by creating access token and refresh token for the user. Here, the simple flow is like:

We will generate an access token and a refresh-token based on a user Then we can secure other operations using these tokens. Hence, we will use the “access token” to validate them There will be expiration time for each token which we can change but by default, it is 15 minutes When tokens are expired, we can refresh the tokens using the “refresh token” query and then we can use the new token for more queries/mutations

I hope the above points make sense.

We will be using decorators in our queries and mutations so make the objects secure. Add below line before you use the authentication decorators, so basically somewhere on the top of your file after you configure your flask app:

auth = GraphQLAuth(app)

So now let’s generate our tokens for the registered user and add it to the Mutation class:

Congratulations !! if you have got your first tokens successfully

Now there are two ways that the client can pass this token:

As a parameter in the query In the header of the request

Let’s see the first approach when we create the store.

JWT as a parameter

Here you just need to add “@mutation_jwt_required” decorator to authenticate before the mutation occurs and add a token field into the Arguments to retrieve it from the query parameter.

Now here if you noticed that I have defined the “ProtectedStore” that is the union of the “StoreObject” and “AuthInfoField” which is important because if there is an error like “token expired” then the client will be notified.

Now let’s try it out using the “access token” that you have generated at the beginning of the Authentication:

Now let’s develop the second approach by querying the Store where we will pass access token into the header of the request:

JWT in the request header:

Here, to pass access token I have used Insomnia as a client to request. You can download the same software and use to send GraphQL queries.

Headers:

“Authorization”: “bearer {access_token}”

Let me show you when I used an expired token I got the proper message in the response and that is the importance of using the “AuthInfoField” in the union.

Now let’s use the latest valid token:

Hope you have got the successful results.

Now if you are wondering “how do we refresh the token?”, just add this simple mutation where the client has to provide the old/current token in the query or in the header(below code is for the token as a parameter):

Refresh token

Now I hope you are able to develop a secure Flask app with GraphQL. In addition, you can change decorators as per your requirements and also change the auth configurations. More information on that you can find over here — https://flask-graphql-auth.readthedocs.io/en/latest/options.html

Please let me know if you have any queries in the comment section. I will try to get back to you. Thank you for reading this article and hope you enjoyed it.

Hit the clap if you liked it.

Happy learning! Happy coding!