# Python authorization libraries

Python authorization libraries decide whether an authenticated user may perform an action on a resource. A policy engine evaluates each request against roles, attributes, or relationships stored in a policy model. These libraries let apps and AI agents enforce permissions in one place instead of scattering checks through the code.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Authlib](#authlib) | 137.9M | 5.5K | Nov 2026 | BSD-3-Clause |
| [Django](#django) | 51.9M | 91.8K | Nov 2026 | BSD-3-Clause |
| [Django REST framework](#djangorestframework) | 30.2M | 30.2K | Oct 2026 | BSD-3-Clause |
| [Django OAuth Toolkit](#django-oauth-toolkit) | 6.8M | 3.3K | Aug 2026 | BSD-2-Clause-Views |
| [OpenFGA](#openfga-sdk) | 3.2M | 88 | Nov 2026 | Apache-2.0 |
| [PyCasbin](#pycasbin) | 2.4M | 1.8K | Feb 2026 | Apache-2.0 |
| [Authzed](#authzed) | 1.3M | 51 | Jul 2026 | Apache-2.0 |
| [django-guardian](#django-guardian) | 1.1M | 3.9K | Oct 2026 | BSD-2-Clause; CC-BY-4.0 (icons) |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[OpenFGA](#openfga-sdk) has the most monthly downloads among dedicated authorization libraries in this comparison, at 3.2M.

## Capabilities

| Library | Object grant storage | Separate policy server |
| --- | --- | --- |
| [Authlib](#authlib) | No | No |
| [Django](#django) | No | No |
| [Django REST framework](#djangorestframework) | No | No |
| [Django OAuth Toolkit](#django-oauth-toolkit) | No | No |
| [OpenFGA](#openfga-sdk) | Yes | Yes |
| [PyCasbin](#pycasbin) | Yes | No |
| [Authzed](#authzed) | Yes | Yes |
| [django-guardian](#django-guardian) | Yes | No |

## Libraries

### Authlib

[GitHub](https://github.com/authlib/authlib) · [PyPI](https://pypi.org/project/authlib) · [Docs](https://docs.authlib.org/en/stable/)

Builds OAuth and OpenID Connect servers and clients.

- Downloads / mo: 137.9M
- Stars: 5.5K
- Last release: 1.9.9
- License: BSD-3-Clause
- Capabilities: [From the Authlib docs](https://docs.authlib.org/en/stable/)

```sh
pip install Authlib
```

**authlib/example-oauth2-server** (702 stars)

[authlib/example-oauth2-server](https://github.com/authlib/example-oauth2-server) 

```python
@bp.route("/oauth/authorize", methods=["GET", "POST"])
def authorize():
    user = current_user()
    if not user:
        return redirect(
            url_for("home.home", next=request.script_root + request.full_path)
        )

    try:
        grant = authorization.get_consent_grant(end_user=user)
    except OAuth2Error as error:
        return authorization.handle_error_response(request, error)

    if request.method == "GET":
        return render_template("authorize.html", user=user, grant=grant)

    grant_user = user if "confirm" in request.form else None
    return authorization.create_authorization_response(
        grant=grant, grant_user=grant_user
    )

```

[src/website/routes.py](https://github.com/authlib/example-oauth2-server/blob/48f26d549359d189b1c1e75ade96f14d860a8bd1/src/website/routes.py#L107-L126) · [More projects using Authlib →](https://dashboard.exa.ai/playground/search?q=authlib%20GitHub%20projects)

**Quickstart**

```python
from authlib.oauth2.rfc6750 import BearerTokenValidator

validator = BearerTokenValidator()
print(validator.scope_insufficient("read:docs", ["read:docs"]))

```

From [resource_protector.py](https://github.com/authlib/authlib/blob/main/authlib/oauth2/rfc6749/resource_protector.py)

### Django

[GitHub](https://github.com/django/django) · [PyPI](https://pypi.org/project/Django) · [Docs](https://docs.djangoproject.com/en/stable/)

Provides a high-level Python web framework.

- Downloads / mo: 51.9M
- Stars: 91.8K
- Last release: 6.1.3
- License: BSD-3-Clause
- Capabilities: [From the Django docs](https://docs.djangoproject.com/en/stable/)

```sh
python -m pip install Django
```

**wagtail/wagtail** (20.7K stars)

[wagtail/wagtail](https://github.com/wagtail/wagtail) 

```python
def instances_user_has_any_permission_for(self, user, actions):
    if user.is_active and user.is_superuser:
        # active superusers can perform any action (including unrecognised ones)
        # on any instance
        return self.model._default_manager.all()
    elif "change" in actions or "delete" in actions:
        if user.has_perm(self._get_permission_name("change")):
            # user can edit all instances
            return self.model._default_manager.all()
        elif user.has_perm(self._get_permission_name("add")):
            # user can edit their own instances
            return self.model._default_manager.filter(
                **{self.owner_field_name: user}
            )
        else:
            # user has no permissions at all on this model
            return self.model._default_manager.none()
    else:
        # action is either not recognised, or is the 'add' action which is
        # not meaningful for existing instances. As such, non-superusers
        # cannot perform it on any existing instances.
        return self.model._default_manager.none()

```

[wagtail/permission_policies/base.py](https://github.com/wagtail/wagtail/blob/79eeb4b94dae7761c8e8ff76bf0a29c4b17ace32/wagtail/permission_policies/base.py#L404-L425) · [More projects using Django →](https://dashboard.exa.ai/playground/search?q=Django%20GitHub%20projects)

**Quickstart**

```python
from django.conf import settings
settings.configure(
    SECRET_KEY="quickstart-example-only",
    INSTALLED_APPS=["django.contrib.auth", "django.contrib.contenttypes"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
import django
django.setup()
from django.core.management import call_command
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission

call_command("migrate", verbosity=0)
user = get_user_model().objects.create_user(username="library_demo")
permission = Permission.objects.get(content_type__app_label="auth", codename="view_user")
user.user_permissions.add(permission)
print(user.has_perm("auth.view_user"))

```

From [models.py](https://github.com/django/django/blob/main/django/contrib/auth/models.py)

### Django REST framework

[GitHub](https://github.com/encode/django-rest-framework) · [PyPI](https://pypi.org/project/djangorestframework) · [Docs](https://www.django-rest-framework.org/)

Builds web APIs for Django.

- Downloads / mo: 30.2M
- Stars: 30.2K
- Last release: 3.18.3
- License: BSD-3-Clause
- Capabilities: [From the Django REST framework docs](https://www.django-rest-framework.org/)

```sh
pip install djangorestframework
```

**netbox-community/netbox** (21.9K stars)

[netbox-community/netbox](https://github.com/netbox-community/netbox) 

```python
def retrieve(self, request, *args, **kwargs):
    instance = self.get_object()
    serializer = self.get_serializer(instance)
    response = Response(serializer.data)
    if etag := self._get_etag(instance):
        response['ETag'] = etag
    return response

```

[netbox/netbox/api/viewsets/__init__.py](https://github.com/netbox-community/netbox/blob/691bb37fb891f64803eb7ec56fe5ebba287b0efe/netbox/netbox/api/viewsets/__init__.py#L77-L83) · [More projects using Django REST framework →](https://dashboard.exa.ai/playground/search?q=djangorestframework%20GitHub%20projects)

**Quickstart**

```python
from django.conf import settings
settings.configure(
    SECRET_KEY="quickstart-example-only",
    INSTALLED_APPS=["django.contrib.auth", "django.contrib.contenttypes", "rest_framework"],
)
import django
django.setup()

from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.test import APIRequestFactory
from rest_framework.views import APIView

class AdminView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        return Response({"status": "ok"})

response = AdminView.as_view()(APIRequestFactory().get("/"))
print(response.status_code)

```

From [permissions.py](https://github.com/encode/django-rest-framework/blob/main/rest_framework/permissions.py)

### Django OAuth Toolkit

[GitHub](https://github.com/django-oauth/django-oauth-toolkit) · [PyPI](https://pypi.org/project/django-oauth-toolkit) · [Docs](https://django-oauth-toolkit.readthedocs.io/)

Runs an OAuth authorization server inside Django.

- Downloads / mo: 6.8M
- Stars: 3.3K
- Last release: 3.4.1
- License: BSD-2-Clause-Views
- Capabilities: [From the Django OAuth Toolkit docs](https://django-oauth-toolkit.readthedocs.io/)

```sh
pip install django-oauth-toolkit
```

**Quickstart**

```python
import os
import django
django.setup()

from django.http import HttpResponse
from django.test import RequestFactory
from oauth2_provider.views.generic import ProtectedResourceView

class ApiEndpoint(ProtectedResourceView):
    def get(self, request, *args, **kwargs):
        return HttpResponse("Hello, OAuth2!")

request = RequestFactory().get(
    "/api/hello", secure=True, HTTP_HOST="localhost",
    HTTP_AUTHORIZATION="Bearer " + os.environ["OAUTH_ACCESS_TOKEN"],
)
print(ApiEndpoint.as_view()(request).status_code)

```

From [README.md](https://github.com/django-oauth/django-oauth-toolkit/blob/master/docs/tutorial/tutorial_02.rst) · [Find projects using Django OAuth Toolkit →](https://dashboard.exa.ai/playground/search?q=django-oauth-toolkit%20GitHub%20projects)

### OpenFGA

[GitHub](https://github.com/openfga/python-sdk) · [PyPI](https://pypi.org/project/openfga-sdk) · [Docs](https://openfga.dev/docs/)

Provides an authorization engine inspired by Google Zanzibar.

- Downloads / mo: 3.2M
- Stars: 88
- Last release: 0.10.6
- License: Apache-2.0
- Capabilities: [From the OpenFGA docs](https://openfga.dev/docs/)

```sh
pip3 install openfga_sdk
```

**Quickstart**

```python
import asyncio
import os
from openfga_sdk import ClientConfiguration, OpenFgaClient
from openfga_sdk.client import ClientCheckRequest

async def main():
    configuration = ClientConfiguration(
        api_url=os.environ["FGA_API_URL"],
        store_id=os.environ["FGA_STORE_ID"],
        authorization_model_id=os.environ["FGA_AUTHORIZATION_MODEL_ID"],
    )
    async with OpenFgaClient(configuration) as client:
        response = await client.check(ClientCheckRequest(
            user="user:anne", relation="viewer", object="document:roadmap",
        ))
        print(response.allowed)

asyncio.run(main())

```

From [README.md](https://github.com/openfga/python-sdk/blob/main/README.md) · [Find projects using OpenFGA →](https://dashboard.exa.ai/playground/search?q=openfga-sdk%20GitHub%20projects)

### PyCasbin

[GitHub](https://github.com/apache/casbin-pycasbin) · [PyPI](https://pypi.org/project/pycasbin) · [Docs](https://casbin.apache.org/)

Enforces authorization policies using configurable access-control models.

- Downloads / mo: 2.4M
- Stars: 1.8K
- Last release: 2.8.0
- License: Apache-2.0
- Capabilities: [From the PyCasbin docs](https://casbin.apache.org/)

**Strengths**

- **Supports multiple access-control models.** Choose role-based, attribute-based, or domain-scoped policy models.
- **Separates models from policy data.** Define the authorization model separately from stored policy rules.

**Watch out for**

- **Authentication stays with the application.** Authenticate the caller before enforcing authorization policies.

```sh
pip install pycasbin
```

**pycasbin/fastapi-authz** (194 stars)

[pycasbin/fastapi-authz](https://github.com/pycasbin/fastapi-authz) 

```python
def _enforce(self, scope: Scope, receive: Receive) -> bool:
    """
    Enforce a request

    :param user: user will be sent to enforcer
    :param request: ASGI Request
    :return: Enforce Result
    """

    request = Request(scope, receive)

    path = request.url.path
    method = request.method
    if 'user' not in scope:
        raise RuntimeError("Casbin Middleware must work with an Authentication Middleware")

    assert isinstance(request.user, BaseUser)

    user = request.user.display_name if request.user.is_authenticated else 'anonymous'

    return self.enforcer.enforce(user, path, method)

```

[fastapi_authz/middleware.py](https://github.com/pycasbin/fastapi-authz/blob/b809e72db587351be9a29102512a573d3f0e8f06/fastapi_authz/middleware.py#L45-L65) · [More projects using PyCasbin →](https://dashboard.exa.ai/playground/search?q=Public%20Python%20projects%20using%20pycasbin%20for%20object%20permissions%2C%20request%20authorization%2C%20role%20policies%20and%20attribute-based%20access%20checks&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import casbin
from casbin.model import Model

model = Model()
model.load_model_from_text("""[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act""")
enforcer = casbin.Enforcer(model)
enforcer.add_policy("alice", "data1", "read")
print(enforcer.enforce("alice", "data1", "read"))

```

From [README.md](https://github.com/apache/casbin-pycasbin/blob/master/README.md)

### Authzed

[GitHub](https://github.com/authzed/authzed-py) · [PyPI](https://pypi.org/project/authzed) · [Docs](https://authzed.com/docs/)

Provides the client library for SpiceDB.

- Downloads / mo: 1.3M
- Stars: 51
- Last release: 1.25.0
- License: Apache-2.0
- Capabilities: [From the Authzed docs](https://authzed.com/docs/)

```sh
pip install authzed
```

**Quickstart**

```python
import os
from authzed.api.v1 import (
    Client, CheckPermissionRequest, CheckPermissionResponse, ObjectReference, SubjectReference,
)
from grpcutil import bearer_token_credentials

client = Client(
    os.environ["AUTHZED_ENDPOINT"],
    bearer_token_credentials(os.environ["AUTHZED_API_TOKEN"]),
)
response = client.CheckPermission(CheckPermissionRequest(
    resource=ObjectReference(object_type="blog/post", object_id="1"),
    permission="reader",
    subject=SubjectReference(object=ObjectReference(object_type="blog/user", object_id="emilia")),
))
print(response.permissionship == CheckPermissionResponse.PERMISSIONSHIP_HAS_PERMISSION)

```

From [README.md](https://github.com/authzed/authzed-py/blob/main/README.md) · [Find projects using Authzed →](https://dashboard.exa.ai/playground/search?q=authzed%20GitHub%20projects)

### django-guardian

[GitHub](https://github.com/django-guardian/django-guardian) · [PyPI](https://pypi.org/project/django-guardian) · [Docs](https://django-guardian.readthedocs.io/)

Adds per-object permissions to Django’s authorization backend.

- Downloads / mo: 1.1M
- Stars: 3.9K
- Last release: 3.5.2
- License: BSD-2-Clause; CC-BY-4.0 (icons)
- Capabilities: [From the django-guardian docs](https://django-guardian.readthedocs.io/)

**Strengths**

- **Stores permissions per object.** Assign a user permission for one object without granting it globally.
- **Supports users and groups.** Assign object permissions to individual users or Django groups.

**Watch out for**

- **Generic relations need deletion cleanup.** Delete object-permission rows when deleting objects linked through generic relations.

```sh
pip install django-guardian
```

**rpkilby/django-rest-framework-guardian** (164 stars)

[rpkilby/django-rest-framework-guardian](https://github.com/rpkilby/django-rest-framework-guardian) 

```python
def filter_queryset(self, request, queryset, view):
    # We want to defer this import until runtime, rather than import-time.
    # See https://github.com/encode/django-rest-framework/issues/4608
    # (Also see #1624 for why we need to make this import explicitly)
    from guardian.shortcuts import get_objects_for_user

    user = request.user
    permission = self.perm_format % {
        'app_label': queryset.model._meta.app_label,
        'model_name': queryset.model._meta.model_name,
    }

    return get_objects_for_user(
        user, permission, queryset,
        **self.shortcut_kwargs)

```

[src/rest_framework_guardian/filters.py](https://github.com/rpkilby/django-rest-framework-guardian/blob/784a9c8958bf12cdceb6f4161f87d9075994318d/src/rest_framework_guardian/filters.py#L14-L28) · [More projects using django-guardian →](https://dashboard.exa.ai/playground/search?q=Public%20Python%20projects%20using%20django-guardian%20for%20object%20permissions%2C%20request%20authorization%2C%20role%20policies%20and%20attribute-based%20access%20checks&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from django.conf import settings
settings.configure(
    SECRET_KEY="quickstart-example-only",
    INSTALLED_APPS=["django.contrib.auth", "django.contrib.contenttypes", "guardian"],
    AUTHENTICATION_BACKENDS=["django.contrib.auth.backends.ModelBackend", "guardian.backends.ObjectPermissionBackend"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
import django
django.setup()
from django.core.management import call_command
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from guardian.shortcuts import assign_perm

call_command("migrate", verbosity=0)
user = get_user_model().objects.create_user(username="library_demo")
group = Group.objects.create(name="editable_demo")
assign_perm("change_group", user, group)
print(user.has_perm("auth.change_group", group))

```

From [README.md](https://github.com/django-guardian/django-guardian/blob/main/guardian/shortcuts.py)

## FAQ

### Which Python authorization library should I use?

[PyCasbin](#pycasbin) suits apps that want role or attribute policies in a config file. [OpenFGA](#openfga-sdk) and [Authzed](#authzed) suit relationship-based permissions shared across services. [django-guardian](#django-guardian) suits Django apps that need per-object permissions.

### ABAC vs RBAC: what is the difference?

Role-based access control grants permissions through roles assigned to users. Attribute-based access control evaluates attributes of the user, the resource, and the request, such as department or time of day.

### Authorization vs authentication: what is the difference?

Authentication confirms who a user is. Authorization decides what that user may do after sign-in.

### What is SpiceDB?

SpiceDB is an open-source permissions database inspired by Google Zanzibar. [Authzed](#authzed) is its Python client library.

### What is OpenFGA?

OpenFGA is an open-source authorization engine inspired by Google Zanzibar. Its [Python SDK](#openfga-sdk) writes relationship tuples and checks permissions.

### What is ReBAC?

Relationship-based access control grants access from relationships between objects, such as a user who owns a folder. OpenFGA and SpiceDB both implement this model.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python authorization libraries PyCasbin rules django-guardian py-abac code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
