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

#658: fix for async Auth #756

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions docs/docs/guides/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,4 +174,29 @@ the same way an operation would:
{!./src/tutorial/authentication/bearer02.py!}
```

## Async authentication

**Django Ninja** has basic support for asynchronous authentication. While the default authentication classes are not async-compatible, you can still define your custom asynchronous authentication callables and pass them in using `auth`.

```python hl_lines="3 12"
from ninja.security import HttpBearer

async def async_auth(request):
...

@api.get("/pets", auth=async_auth)
def pets(request):
...

# Also
class AsyncBearerAuth(HttpBearer):
def authenticate(self, request, token):
...

@api.get("/pets", auth=AsyncBearerAuth())
def pets(request):
...
```


See [Handling errors](errors.md) for more information.
11 changes: 9 additions & 2 deletions ninja/operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
cast,
)

from asgiref.sync import async_to_sync, sync_to_async
import django
import pydantic
from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed
Expand All @@ -21,6 +22,7 @@
from ninja.errors import AuthenticationError, ConfigError, ValidationError
from ninja.params_models import TModels
from ninja.schema import Schema
from ninja.security.base import AuthBase
from ninja.signature import ViewSignature, is_async
from ninja.types import DictStrAny
from ninja.utils import check_csrf
Expand Down Expand Up @@ -147,7 +149,12 @@ def _run_checks(self, request: HttpRequest) -> Optional[HttpResponse]:
def _run_authentication(self, request: HttpRequest) -> Optional[HttpResponse]:
for callback in self.auth_callbacks:
try:
result = callback(request)
if is_async(callback):
result = async_to_sync(callback)(request)
elif isinstance(callback, AuthBase) and is_async(callback.authenticate):
result = async_to_sync(callback)(request)
else:
result = callback(request)
except Exception as exc:
return self.api.on_exception(request, exc)

Expand Down Expand Up @@ -256,7 +263,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
self.is_async = True

async def run(self, request: HttpRequest, **kw: Any) -> HttpResponseBase: # type: ignore
error = self._run_checks(request)
error = await sync_to_async(self._run_checks)(request)
if error:
return error
try:
Expand Down
83 changes: 83 additions & 0 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,34 @@ def callable_auth(request):
return request.GET.get("auth")


async def async_callable_auth(request):
return request.GET.get("auth")


class KeyQuery(APIKeyQuery):
def authenticate(self, request, key):
if key == "keyquerysecret":
return key


class AsyncKeyQuery(APIKeyQuery):
async def authenticate(self, request, key):
if key == "keyquerysecret":
return key


class KeyHeader(APIKeyHeader):
def authenticate(self, request, key):
if key == "keyheadersecret":
return key


class AsyncKeyHeader(APIKeyHeader):
async def authenticate(self, request, key):
if key == "keyheadersecret":
return key


class CustomException(Exception):
pass

Expand All @@ -44,24 +60,49 @@ def authenticate(self, request, key):
return key


class AsyncKeyHeaderCustomException(APIKeyHeader):
async def authenticate(self, request, key):
if key != "keyheadersecret":
raise CustomException
return key


class KeyCookie(APIKeyCookie):
def authenticate(self, request, key):
if key == "keycookiersecret":
return key


class AsyncKeyCookie(APIKeyCookie):
async def authenticate(self, request, key):
if key == "keycookiersecret":
return key


class BasicAuth(HttpBasicAuth):
def authenticate(self, request, username, password):
if username == "admin" and password == "secret":
return username


class AsyncBasicAuth(HttpBasicAuth):
async def authenticate(self, request, username, password):
if username == "admin" and password == "secret":
return username


class BearerAuth(HttpBearer):
def authenticate(self, request, token):
if token == "bearertoken":
return token


class AsyncBearerAuth(HttpBearer):
async def authenticate(self, request, token):
if token == "bearertoken":
return token


def demo_operation(request):
return {"auth": request.auth}

Expand All @@ -78,12 +119,19 @@ def on_custom_error(request, exc):
("django_auth", django_auth),
("django_auth_superuser", django_auth_superuser),
("callable", callable_auth),
("async_callable", async_callable_auth),
("apikeyquery", KeyQuery()),
("async_apikeyquery", AsyncKeyQuery()),
("apikeyheader", KeyHeader()),
("async_apikeyheader", AsyncKeyHeader()),
("apikeycookie", KeyCookie()),
("async_apikeycookie", AsyncKeyCookie()),
("basic", BasicAuth()),
("async_basic", AsyncBasicAuth()),
("bearer", BearerAuth()),
("async_bearer", AsyncBearerAuth()),
("customexception", KeyHeaderCustomException()),
("async_customexception", AsyncKeyHeaderCustomException()),
]:
api.get(f"/{path}", auth=auth, operation_id=path)(demo_operation)

Expand Down Expand Up @@ -124,22 +172,40 @@ class MockSuperUser(str):
),
("/callable", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
("/callable?auth=demo", {}, 200, dict(auth="demo")),
("/async_callable", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
("/async_callable?auth=demo", {}, 200, dict(auth="demo")),
("/apikeyquery", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
("/apikeyquery?key=keyquerysecret", {}, 200, dict(auth="keyquerysecret")),
("/async_apikeyquery", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
("/async_apikeyquery?key=keyquerysecret", {}, 200, dict(auth="keyquerysecret")),
("/apikeyheader", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
(
"/apikeyheader",
dict(headers={"key": "keyheadersecret"}),
200,
dict(auth="keyheadersecret"),
),
("/async_apikeyheader", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
(
"/async_apikeyheader",
dict(headers={"key": "keyheadersecret"}),
200,
dict(auth="keyheadersecret"),
),
("/apikeycookie", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
(
"/apikeycookie",
dict(COOKIES={"key": "keycookiersecret"}),
200,
dict(auth="keycookiersecret"),
),
("/async_apikeycookie", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
(
"/async_apikeycookie",
dict(COOKIES={"key": "keycookiersecret"}),
200,
dict(auth="keycookiersecret"),
),
("/basic", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
(
"/basic",
Expand Down Expand Up @@ -185,6 +251,13 @@ class MockSuperUser(str):
200,
dict(auth="keyheadersecret"),
),
("/async_customexception", {}, 401, dict(custom=True)),
(
"/async_customexception",
dict(headers={"key": "keyheadersecret"}),
200,
dict(auth="keyheadersecret"),
),
],
)
def test_auth(path, kwargs, expected_code, expected_body, settings):
Expand All @@ -199,11 +272,21 @@ def test_schema():
schema = api.get_openapi_schema()
assert schema["components"]["securitySchemes"] == {
"BasicAuth": {"scheme": "basic", "type": "http"},
"AsyncBearerAuth": {"scheme": "bearer", "type": "http"},
"BearerAuth": {"scheme": "bearer", "type": "http"},
"AsyncBasicAuth": {"scheme": "basic", "type": "http"},
"KeyCookie": {"in": "cookie", "name": "key", "type": "apiKey"},
"AsyncKeyCookie": {"in": "cookie", "name": "key", "type": "apiKey"},
"KeyHeader": {"in": "header", "name": "key", "type": "apiKey"},
"AsyncKeyHeader": {"in": "header", "name": "key", "type": "apiKey"},
"KeyHeaderCustomException": {"in": "header", "name": "key", "type": "apiKey"},
"AsyncKeyHeaderCustomException": {
"in": "header",
"name": "key",
"type": "apiKey",
},
"KeyQuery": {"in": "query", "name": "key", "type": "apiKey"},
"AsyncKeyQuery": {"in": "query", "name": "key", "type": "apiKey"},
"SessionAuth": {"in": "cookie", "name": "sessionid", "type": "apiKey"},
"SessionAuthSuperUser": {"in": "cookie", "name": "sessionid", "type": "apiKey"},
}
Expand Down