Integrations
In order to simplify implementing your own OIDC based API endpoints, allauth offers out of the box support for authenticating and authorizing requests with Django Ninja as well as Django REST framework.
Django Ninja
For Django Ninja, the following security class is available:
- class allauth.idp.oidc.contrib.ninja.security.TokenAuth(scope: str | list | dict)
Use the OIDC access token to authenticate and the scopes attached to the token to authorize the request.
- __init__(scope: str | list | dict)
The scope passed can either be:
a single scope (
str),a list of scopes, all of which should be granted.
a list of scope lists. Your token should match at least all scopes of one of the scope lists.
A dictionary, with the request method (e.g.
GET) as key, and one of the scope values from the previous bullet. The scopes to match are then dynamically selected based on the request.
An example on how to use that security class in your own code is listed below:
from allauth.idp.oidc.contrib.ninja.security import TokenAuth
from ninja import NinjaAPI
api = NinjaAPI()
@api.get("/api/resource", auth=[TokenAuth(scope=["view-resource"])])
def resource(request):
...
Django REST framework
For Django REST framework, the following authentication class is available:
- class allauth.idp.oidc.contrib.rest_framework.authentication.TokenAuthentication
Use the OIDC access token to authenticate the request.
- class allauth.idp.oidc.contrib.rest_framework.permissions.TokenPermission
- classmethod has_scope(scope: str | list | dict)
Constructs and returns specific permission class (not instance) that checks that the request is authenticated by means of a token (see:
TokenAuthentication), and, that this token has the specifiedscopegranted.The scope passed can either be:
a single scope (
str),a list of scopes, all of which should be granted.
a list of scope lists. Your token should match at least all scopes of one of the scope lists.
A dictionary, with the request method (e.g.
GET) as key, and one of the scope values from the previous bullet. The scopes to match are then dynamically selected based on the request.
An example on how to use that authentication class in your own code is listed below:
from rest_framework.views import APIView
from allauth.idp.oidc.contrib.rest_framework.authentication import TokenAuthentication
from allauth.idp.oidc.contrib.rest_framework.permissions import TokenPermission
class ResourceView(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [TokenPermission.has_scope(["view-resource"])]
def get(request, *args, **kwargs):
...