Authentication

Creating a User

Django already comes with the concept of Users built in. Before talking about authentication, let’s create our first User.

To do it so, we need to send data to the server through a mutation.

In this mutation the server will receive a username, password and email, returning the created user information. Remember that on your last mutation – 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 on the GraphiQL interface:

On the response, you already can see the new user. Hurray!

Querying the Users

Let’s create a query for listing all users:

To test it, send a query to the server:

User Authentication

The concept of authentication and authorization is enabled by default on 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 sings up or logs in a token will be returned: a piece of data that identify 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 JTW site above.

Unfortunally, 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 here.

Configuring django-graphql-jwt

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.

VeriryToken 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 enable to expire. Using it is outside the scope of this tutorial.

Besides that, various aspects of the Mutations and JWT can be configured on the library. Please check the documentation for more information.

Testing the authentication

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 VerifyToken Mutation and use it in our Query with the AUTHORIZATION HTTP header, using the JWT prefix. Now, we are going to the Inmsonia client:

Under the Header tab on Inmsonia, add the AUTHORIZATION HTTP header with your token content, prefixed by the word JWT:

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.

Unlock the next chapter
Which is the best way to authorize users in the modern web?
Sessions
Cookies
Tokens
Local Storage