All-in-One JWT Authentication plugin for Strawberry
Project description
Chowkidar
A simple, flexible JWT authentication plugin for your Django Strawberry GraphQL APIs.
Installation
- Install the package from PyPI:
pip install chowkidar-strawberry
- Add
chowkidar_strawberry
to yourINSTALLED_APPS
:
INSTALLED_APPS = [
...
"chowkidar",
]
- Add
chowkidar.extensions.JWTAuthExtension
to your strawberry schema extensions:-
from chowkidar.extension import JWTAuthExtension
schema = strawberry.Schema(
query=Query,
mutation=Mutation,
extensions=[JWTAuthExtension],
)
- Wrap your Strawberry GraphQL view with
chowkidar.view.auth_enabled_view
:
from chowkidar.view import auth_enabled_view
urlpatterns = [
...
path(
"graphql/",
auth_enabled_view(
GraphQLView.as_view(schema=schema, graphiql=settings.DEBUG)
)
),
]
- Create a Refresh Token Model inheriting the
chowkidar.models.AbstractRefreshToken
abstract model:
class RefreshToken(AbstractRefreshToken, models.Model):
pass
(do not forget run to python manage.py makemigrations
and python manage.py migrate
)
- Implement Mutations for
login
andlogout
withissue_tokens_on_login
andrevoke_tokens_on_logout
respectively:
import strawberry
from chowkidar.wrappers import issue_tokens_on_login, revoke_tokens_on_logout
@strawberry.type
class AuthMutations:
@strawberry.mutation
@issue_tokens_on_login
def login(self, info, username: str, password: str) -> bool:
user = authenticate(username=username, password=password)
if user is None:
raise Exception("Invalid username or password")
# Set LOGIN_USER with the authenticated user's object, in case of successful authentication
# else, set LOGIN_USER to None
info.context.LOGIN_USER = user
return True
@strawberry.mutation
@revoke_tokens_on_logout
def logout(self, info) -> bool:
# Set info.context.LOGIN_USER to True for logging out the user
info.context.LOGOUT_USER = True
return True
All your resolvers will now get the following parameters from info.context
-
info.context.userID
- ID of the requesting user, None if not logged-ininfo.context.refreshToken
- Refresh token string of the requesting user, None if not logged-ininfo.context.IPAddress
- IP Address of the requesting user
Decorators
You can use these decorators
@login_required
- wrap your resolver with this decorator to ensure the resolver is called only for logged-in users.
from chowkidar.decorators import login_required
@strawberry.type
class Query:
@strawberry.field
@login_required
def movies(self, info) -> List[MovieType]:
return Movie.objects.all()
@resolve_user
- wrap this around your resolver to obtainUser
model instance of the requesting user atinfo.context.user
. Hits the Database. Will throw an exception if the user is not logged-in.
from chowkidar.decorators import resolve_user
@strawberry.type
class Mutation:
@strawberry.mutation
@resolve_user
def create_movie(self, name: str, info) -> List[MovieType]:
if not info.context.user.is_superuser:
raise Exception("Only superusers can create movies")
# Note: Like you see here, for most queryset operations you can use - user_id=info.context.userID, without needing any decorator or hitting the DB.
return Movie.objects.create(name=name, user_id=info.context.userID)
Settings
Here are the available settings -
REFRESH_TOKEN_MODEL = None # Required, a model that implements chowkidar.models.AbstractRefreshToken
JWT_REFRESH_TOKEN_N_BYTES: int = 20
# Expiry Settings
JWT_ACCESS_TOKEN_EXPIRATION_DELTA: timedelta = timezone.timedelta(seconds=60)
JWT_REFRESH_TOKEN_EXPIRATION_DELTA: timedelta = timezone.timedelta(seconds=60 * 60 * 24 * 7)
# Cookie Settings
JWT_ACCESS_TOKEN_COOKIE_NAME: str = 'JWT_ACCESS_TOKEN'
JWT_REFRESH_TOKEN_COOKIE_NAME: str = 'JWT_REFRESH_TOKEN'
JWT_COOKIE_DOMAIN: str = None
JWT_COOKIE_SAME_SITE: ['Lax', 'Strict', 'None'] = "Lax"
JWT_COOKIE_SECURE: bool = False
JWT_COOKIE_HTTP_ONLY: bool = True
# JWT Settings
JWT_SECRET_KEY: str = settings.SECRET_KEY
)
JWT_PUBLIC_KEY: str = None
JWT_PRIVATE_KEY: str = None
JWT_ALGORITHM: str = "HS256"
JWT_LEEWAY: int = 0
JWT_ISSUER: str = None
How it Works?
- Uses short-lived stateless JWT Access Token set as cookie to authenticate users. An additional, long-running stateful JWT Refresh Token, that is recorded in RefreshToken model, is also generated to automatically to allow refreshing / generating new access token when expired. This process is fully managed automatically at the backend. For issuing new access token using a existing refresh token, the refresh token is validated against the DB. For all other requests, the DB is not hit, but access key is simply validated against its key.
settings.py
enlists various configuration options for this plugin. The default values are set to work out of the box with minimal configuration. You can override these values in your project'ssettings.py
to customize the behavior.- Uses a custom Strawberry Extension to read JWT cookies from the
request, for validation, and auto issuing new access token using refresh token when available. Also sets up
info.context.userID
for easy access to the authenticated user's ID in resolvers. This extension is valid throughout the resolving period of the GraphQL request, although auth is processed before actual query execution. This is defined inextensions.py
. - Uses a wrapper function that wraps the GraphQLView to manage cookies. Data for the cookies is sent to this function
via setting custom attribute in
request
object fromextensions.py
. This function executes after GraphQL has been fully processed and http response is ready. This is defined inview.py
. - Consumer applications can custom write login/logout mutations, by wrapping those with
@issue_tokens_on_login
and@revoke_tokens_on_logout
decorators. These are defined inwrappers.py
- Consumer APIs can decorate auth requiring resolvers with
@login_required
(or@resolve_user
), as well as get get the ID of the requesting user frominfo.context.userID
. The decorators are defined indecorators.py
.
Acknowledgement
This project is inspired by django-graphql-jwt & django-graphql-social-auth by flavors.
Contribution
Contributions are welcome. Please open an issue or a PR.
License
This project is licensed under the GNU General Public License V3.
Made by Traboda with ❤️ in India 🇮🇳.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file chowkidar-strawberry-0.2.0.tar.gz
.
File metadata
- Download URL: chowkidar-strawberry-0.2.0.tar.gz
- Upload date:
- Size: 25.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.1 CPython/3.9.13
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 66be814a3c442fb592781e92c06cf27e8c5ff208e36063e9e4745a02d6f6885e |
|
MD5 | b33db71328df296e9b7d9bda6f7fa541 |
|
BLAKE2b-256 | 03d41aff0cff062fc3c3f4e4b00a53b4bcbb4f2bada3f164c8289f05eaee1a83 |