Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to setup ASGI CORS in Django? #8

Open
Saugatkafley opened this issue Oct 16, 2022 · 4 comments
Open

How to setup ASGI CORS in Django? #8

Saugatkafley opened this issue Oct 16, 2022 · 4 comments

Comments

@Saugatkafley
Copy link

I was unable to setup CORS in asgi application . I saw all the instructions but unable to understand where to place them . It didn't work in the base.py .

@simonw
Copy link
Owner

simonw commented Oct 16, 2022

What did you try?

Generally I wouldn't suggest using this with Django since Django already has very robust CSRF protection built into the core framework itself: https://docs.djangoproject.com/en/4.1/ref/csrf/

@Saugatkafley
Copy link
Author

Is there a way to implement using ours in django?

@moritz89
Copy link

moritz89 commented Feb 3, 2025

A reason is if Django is used with Strawberry GraphQL which provides a parallel view. This has the effect that Django's middleware is not run for all paths (e.g., /graphql/).

One option to integrate it is (abbreviated from my implementation):

# asgi.py

from django.conf import settings
from django.core.asgi import get_asgi_application
from django.urls import re_path
from strawberry.channels import GraphQLHTTPConsumer

# Import middlewares and the Strawberry schema after creating the django ASGI application.
# This ensures django.setup() has been called before any ORM models are imported

from myapp.graphql.schema import schema

django_asgi_app = get_asgi_application()
gql_http_consumer = GraphQLHTTPConsumer.as_asgi(schema=schema)

application = ProtocolTypeRouter(
    {
        "http": URLRouter(
            [
                re_path("^graphql/", gql_http_consumer),
                re_path("^", django_asgi_app),
            ]
        )
    }
)


def SecurityStack(app):
    """CORS and AllowedHost Checks."""

    return asgi_cors(
        app,
        hosts=["https://app.example.com"],
        methods=["POST"],
        headers=["Content-Type, Authorization"],
        max_age=86400,
    )


application = SecurityStack(application)

And then you start the ASGI server with: daphne myapp.asgi:application

@moritz89
Copy link

moritz89 commented Feb 3, 2025

After further research I'd suggest using CORSMiddleware from Starlette. The behavior of this library does not conform to the spec in a few scenarios and that one will and can integrated into asgi Django in a similar manner as stated above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants