Django already comes with the concept of Users built in. Before talking about authentication, let’s create our first User.
To do so, we need to send data to the server through a mutation.
In this mutation the server will receive a
CreateLink – the mutation returned field by field, now, you are returning a full
User, where the client can ask the fields it wants.
Execute the following code in the GraphiQL interface:
In the response, you already can see the new user. Hurray!
Let’s create a query for listing all users:
To test it, send a query to the server:
The concept of authentication and authorization is enabled by default in Django using sessions. Since most of the web apps today are stateless, we are going to use the django-graphql-jwt library to implement JWT Tokens in Graphene (thanks mongkok!).
Basically, when a User signs up or logs in, a token will be returned: a piece of data that identifies the User. This token must be sent by the User in the HTTP Authorization header with every request when authentication is needed. If you want to know more about how the token is generated, take a look at the JWT site above.
Unfortunately, the GraphiQL web interface that we used before does not accept adding custom HTTP headers. From now on, we will be using the Insomnia desktop app. You can download and install it from here.
The library creates three Mutations for us, let’s take a look at them.
TokenAuth is used to authenticate the User with its username and password to obtain the JSON Web token.
VerifyToken to confirm that the token is valid, passing it as an argument.
RefreshToken to obtain a new token within the renewed expiration time for non-expired tokens, if they are enabled to expire. Using it is outside the scope of this tutorial.
Besides that, various aspects of the Mutations and JWT can be configured in the library. Please check the documentation for more information.
To test if our authentication is working, let’s create a Query called
me, which should return the User’s information if logged in or an error otherwise.
To test it out, we need to get a token using the
tokenAuth Mutation and use it in our Query with the
AUTHORIZATION HTTP header, using the
JWT prefix. Now, we are going to use the Insomnia client:
Header tab on Insomnia, add the
AUTHORIZATION HTTP header with your token content, prefixed by the word
Finally, let’s make the
me query, which should identify our User:
Awww yeah! You are now able to create users and sign in with them. Try to make the query without the HTTP header and an error message should appear.