Skip to main content

A django app to implement token based authentication in Ariadne GraphQL

Project description

ariadne-token-auth

A django app to implement token based authentication in projects which use ariadne.

Summary

Installing

The package can be downloaded from its github repository.

pip install git+https://github.com/IgnisDa/ariadne-token-auth.git

Or using poetry

poetry add git+https://github.com/IgnisDa/ariadne-token-auth.git#main

Using the package

Example Project

You can have a look at the example project for a fully working project. Habitrac is also a production website which uses this package to implement authentication.

Setup

Include the AuthTokenMiddleware in your MIDDLEWARE settings.

MIDDLEWARE = [
    # Other middleware
    "ariadne_token_auth.middleware.AuthTokenMiddleware",
]

Include the AuthTokenBackend in your AUTHENTICATION_BACKENDS settings.

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "ariadne_token_auth.backends.AuthTokenBackend",
)

Finally add ariadne_token_auth to your INSTALLED_APPS.

INSTALLED_APPS = [
    # other apps
    'ariadne_token_auth',
]

Migrations

Next, run python manage.py migrate to commit the auth-token model to your database.

Schema

Add the relevant mutations to your GraphQL schema.

from ariadne import MutationType, make_executable_schema
from ariadne_token_auth.api import resolvers

auth_mutation = MutationType()

auth_mutation.set_field("getAuthToken", resolvers.get_auth_token)
auth_mutation.set_field("deleteAuthToken", resolvers.delete_auth_token)
type_defs = """
  type Mutation {
    getAuthToken(identifier: String!, password: String!): AuthTokenPayload!
    deleteAuthToken(token: String!): DeleteTokenPayload!
}
"""

schema = make_executable_schema([type_defs, resolvers.type_defs], auth_mutation)
  • getAuthToken to authenticate an existing user and obtain a corresponding token. The resolver uses the user model's USERNAME_FIELD which by default is username. However it will work with other USERNAME_FIELDs just fine, for example when the default user identifier is email instead of username. The example project does this by defining a custom user model.

    mutation getAuthToken($identifier: String!, $password: String!) {
      getAuthToken(identifier: $identifier, password: $password) {
        error
        auth {
          token
        }
      }
    }
    

    If authentication is successful, you can obtain the auth-token from response.data.getAuthToken.auth.token, and if it is unsuccessful, errors will be present in response.data.getAuthToken.error.

  • deleteAuthToken to delete a logged in user using the above token.

    mutation deleteAuthToken($token: String!) {
      deleteAuthToken(token: $token) {
        status
        error
      }
    }
    

    If the token was correct and deletion was successful, the value of response.data.deleteAuthToken.status will be set to true (or it's equivalent in your frontend language). Otherwise, the error will be present in response.data.deleteAuthToken.error and response.data.deleteAuthToken.status will be set to false.

Protecting Views

You can use the login_required decorator to protect your graphql queries from non-authenticated users.

from ariadne import QueryType
from ariadne_token_auth.decorators import login_required

@query.field("testQuery")
@login_required
def test_query(self, info, *args, **kwargs):
    return {"user": info.context.get("request").user}

Configuration

Settings specific to ariadne-token-auth are stored in the ARIADNE_TOKEN_AUTH dictionary in settings.py file. The defaults can be seen in utils.py file. They can be configured as follows:

# settings.py
ARIADNE_TOKEN_AUTH = {
    'TOKEN_NAME': 'myBearer', # case insensitive
    'TOKEN_LENGTH': 15
}

With the above settings, you will have to send requests in the following fashion (example uses curl, but the basic premise stays the same).

curl 'http://127.0.0.1:8000/graphql/' \
      -H 'Content-Type: application/json' \
      -H 'Authorization: myBearer 8496fda8dedad2235921693717c8dc' \
      --data-binary '{"query":"query {\n  testQuery {\n    user\n  }\n}"}'

Bonus

You can find a very easy way to add your *.graphql files to the django auto-reloader here.

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

See also the list of contributors who participated in this project.

License

This project is licensed under the Apache-2.0 - see the LICENSE.md file for details

Acknowledgements

  1. django-token: Model definitions, middleware and authentication backends adapted from django-tokens package.
  2. ariadne-jwt: Exceptions, and decorators adapted from ariadne-jwt package.

Others

Project bootstrapped using cookiecutter by IgnisDa.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ariadne-token-auth-0.1.2.tar.gz (13.1 kB view details)

Uploaded Source

Built Distribution

ariadne_token_auth-0.1.2-py3-none-any.whl (13.1 kB view details)

Uploaded Python 3

File details

Details for the file ariadne-token-auth-0.1.2.tar.gz.

File metadata

  • Download URL: ariadne-token-auth-0.1.2.tar.gz
  • Upload date:
  • Size: 13.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.5 CPython/3.9.3 Linux/5.11.15-arch1-2

File hashes

Hashes for ariadne-token-auth-0.1.2.tar.gz
Algorithm Hash digest
SHA256 8ecfb97a5107159fddb8992f62d5b5f76148baed7339c711398249a8481eb038
MD5 2cd050208acae447d7ff043ecadcc01e
BLAKE2b-256 26f79e6d0f3e41732e2db50f775a0fc345e0c3dda63a640b4789d2af4489d0ed

See more details on using hashes here.

File details

Details for the file ariadne_token_auth-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for ariadne_token_auth-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 70d54b4b5df4653498b00d69b2c5fc38c02a1782e438650ce02b602404854ad9
MD5 0a55229ce1a67e839d30a92a1d40e093
BLAKE2b-256 2d5ddc3ad62d602376454be00bd78a6223c5a49f4e403ac1a1c270094589f1d7

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page