# Python authentication libraries

Python authentication libraries verify who a user is through passwords, sessions, tokens, or sign-in with an outside identity provider. A web framework extension stores the signed-in user in a session cookie or a signed token. These libraries let web apps and APIs sign users in without writing password and token handling from scratch.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Authlib](#authlib) | 137.9M | 5.5K | Nov 2026 | BSD-3-Clause |
| [Flask-Login](#flask-login-library) | 18.6M | 3.7K | Oct 2023 | MIT |
| [Simple JWT](#djangorestframework-simplejwt) | 8.4M | 4.3K | Jul 2025 | MIT |
| [django-allauth](#django-allauth) | 7.2M | 10.4K | Nov 2026 | MIT |
| [Django OAuth Toolkit](#django-oauth-toolkit) | 6.8M | 3.3K | Aug 2026 | BSD-2-Clause |
| [social-auth-app-django](#social-auth-app-django) | 5.9M | 2.1K | Nov 2026 | BSD-3-Clause |
| [django-otp](#django-otp) | 5.7M | 629 | Oct 2026 | Unlicense |
| [Flask-JWT-Extended](#flask-jwt-extended) | 5.2M | 1.6K | May 2026 | MIT |

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

[Authlib](#authlib) has the most monthly downloads in this comparison, at 137.9M.

## Capabilities

| Library | Django integration | OAuth/OIDC provider |
| --- | --- | --- |
| [Authlib](#authlib) | Yes | Yes |
| [Flask-Login](#flask-login-library) | No | No |
| [Simple JWT](#djangorestframework-simplejwt) | Yes | No |
| [django-allauth](#django-allauth) | Yes | Yes |
| [Django OAuth Toolkit](#django-oauth-toolkit) | Yes | Yes |
| [social-auth-app-django](#social-auth-app-django) | Yes | No |
| [django-otp](#django-otp) | Yes | No |
| [Flask-JWT-Extended](#flask-jwt-extended) | No | No |

## Libraries

### Authlib

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

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/)

```sh
pip install Authlib requests
```

**gradio-app/gradio** (44.1K stars)

[gradio-app/gradio](https://github.com/gradio-app/gradio) 

```python
@app.get("/login/huggingface")
async def oauth_login(request: fastapi.Request):
    """Endpoint that redirects to HF OAuth page."""
    # Define target (where to redirect after login)
    redirect_uri = _generate_redirect_uri(request)
    return await oauth.huggingface.authorize_redirect(request, redirect_uri)  # type: ignore
```

[gradio/oauth.py](https://github.com/gradio-app/gradio/blob/ec06278ed72e5eb73494a9d171ca851d553dc82a/gradio/oauth.py#L94-L99) · [More projects using Authlib →](https://dashboard.exa.ai/playground/search?q=authlib%20GitHub%20projects)

**Quickstart**

```python
from authlib.integrations.requests_client import OAuth2Session

with OAuth2Session("example-client-id", "example-client-secret", scope="user:email") as client:
    uri, state = client.create_authorization_url("https://github.com/login/oauth/authorize")
    print(uri)

```

From [index.html](https://docs.authlib.org/en/stable/oauth2/client/http/index.html)

### Flask-Login

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

Manages user authentication and sessions for Flask.

- Downloads / mo: 18.6M
- Stars: 3.7K
- Last release: 0.6.3
- License: MIT
- Capabilities: [From the Flask-Login docs](https://flask-login.readthedocs.io/)

```sh
pip install flask-login
```

**kizniche/Mycodo** (3.3K stars)

[kizniche/Mycodo](https://github.com/kizniche/Mycodo) 

```python
@blueprint.route("/logout")
@flask_login.login_required
def logout():
    """Log out of the web-ui."""
    user = User.query.filter(User.name == flask_login.current_user.name).first()
    role_name = Role.query.filter(Role.id == user.role_id).first().name
    login_log(user.name,
              role_name,
              request.environ.get('REMOTE_ADDR', 'unknown address'),
              'LOGOUT')
    # flask-login logout
    flask_login.logout_user()

    response = clear_cookie_auth()

    flash(gettext("Successfully logged out"), 'success')
    return response
```

[mycodo/mycodo_flask/routes_authentication.py](https://github.com/kizniche/Mycodo/blob/7541eaa69bb4d0f0c60a06adb11f3879b1ecc7e0/mycodo/mycodo_flask/routes_authentication.py#L369-L385) · [More projects using Flask-Login →](https://dashboard.exa.ai/playground/search?q=flask-login%20GitHub%20projects)

**Quickstart**

```python
import flask
import flask_login

app = flask.Flask(__name__)
app.secret_key = "super secret string"  # Change this!

login_manager = flask_login.LoginManager()
login_manager.init_app(app)

```

From [README.md](https://github.com/maxcountryman/flask-login/blob/main/README.md)

### Simple JWT

[GitHub](https://github.com/jazzband/djangorestframework-simplejwt) · [PyPI](https://pypi.org/project/djangorestframework-simplejwt) · [Docs](https://pypi.org/project/djangorestframework-simplejwt/)

Adds JSON Web Token authentication to Django REST Framework.

- Downloads / mo: 8.4M
- Stars: 4.3K
- Last release: 5.5.1
- License: MIT
- Capabilities: [From the Simple JWT docs](https://pypi.org/project/djangorestframework-simplejwt/)

```sh
pip install djangorestframework-simplejwt
```

**iMerica/dj-rest-auth** (1.9K stars)

[iMerica/dj-rest-auth](https://github.com/iMerica/dj-rest-auth) 

```python
def jwt_encode(user):
    from dj_rest_auth.app_settings import api_settings

    JWTTokenClaimsSerializer = api_settings.JWT_TOKEN_CLAIMS_SERIALIZER

    refresh = JWTTokenClaimsSerializer.get_token(user)
    return refresh.access_token, refresh
```

[dj_rest_auth/utils.py](https://github.com/iMerica/dj-rest-auth/blob/90082e3a4d257c053e5eef3f30f51cc7f55492ee/dj_rest_auth/utils.py#L9-L15) · [More projects using Simple JWT →](https://dashboard.exa.ai/playground/search?q=djangorestframework-simplejwt%20GitHub%20projects)

**Quickstart**

```python
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView

urlpatterns = [
    path("api/token/", TokenObtainPairView.as_view(), name="token_obtain_pair"),
]

```

From [getting_started.rst](https://django-rest-framework-simplejwt.readthedocs.io/en/stable/getting_started.html)

### django-allauth

[GitHub](https://github.com/pennersr/django-allauth) · [PyPI](https://pypi.org/project/django-allauth) · [Docs](https://docs.allauth.org/en/latest/)

Provides integrated Django account registration, management, and authentication.

- Downloads / mo: 7.2M
- Stars: 10.4K
- Last release: 65.22.1
- License: MIT
- Capabilities: [From the django-allauth docs](https://docs.allauth.org/en/latest/)

**Strengths**

- **Combines local and social login.** Use local accounts and external identities in the same account system.
- **Supports passkeys and recovery codes.** Add the MFA extra for passkeys, authenticator codes, and recovery codes.

**Watch out for**

- **Rate limits need shared storage.** Use a shared cache to enforce limits across application workers.
- **IP limits need proxy configuration.** Configure trusted proxies so rate limits use the correct client address.

```sh
pip install django-allauth
```

**iMerica/dj-rest-auth** (1.9K stars)

[iMerica/dj-rest-auth](https://github.com/iMerica/dj-rest-auth) 

```python
def save(self, request):
    adapter = get_adapter()
    user = adapter.new_user(request)
    self.cleaned_data = self.get_cleaned_data()
    user = adapter.save_user(request, user, self, commit=False)
    if "password1" in self.cleaned_data:
        try:
            adapter.clean_password(self.cleaned_data['password1'], user=user)
        except DjangoValidationError as exc:
            raise serializers.ValidationError(
                detail=serializers.as_serializer_error(exc)
            )
    user.save()
    self.custom_signup(request, user)
    setup_user_email(request, user, [])
    return user
```

[dj_rest_auth/registration/serializers.py](https://github.com/iMerica/dj-rest-auth/blob/69ef459bdcd4a4a25121ad2064cc18a6601addb6/dj_rest_auth/registration/serializers.py#L274-L289) · [More projects using django-allauth →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20django-allauth%20for%20user%20authentication&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.urls import include, path

urlpatterns = [path("accounts/", include("allauth.urls"))]

```

From [urls.py](https://github.com/pennersr/django-allauth/blob/main/examples/regular-django/example/urls.py)

### Django OAuth Toolkit

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

Runs an OAuth authorization server inside Django.

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

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

**Quickstart**

```python
from django.urls import include, path

urlpatterns = [
    path("o/", include("oauth2_provider.urls", namespace="oauth2_provider")),
]

```

From [README.md](https://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial_01.html) · [Find projects using Django OAuth Toolkit →](https://dashboard.exa.ai/playground/search?q=django-oauth-toolkit%20GitHub%20projects)

### social-auth-app-django

[GitHub](https://github.com/python-social-auth/social-app-django) · [PyPI](https://pypi.org/project/social-auth-app-django) · [Docs](https://pypi.org/project/social-auth-app-django/)

Integrates Python Social Auth with Django.

- Downloads / mo: 5.9M
- Stars: 2.1K
- Last release: 8.1.0
- License: BSD-3-Clause
- Capabilities: [From the social-auth-app-django docs](https://pypi.org/project/social-auth-app-django/)

```sh
pip install social-auth-app-django
```

**zulip/zulip** (26.3K stars)

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

```python
@csrf_exempt
def saml_sp_metadata(request: HttpRequest) -> HttpResponse:  # nocoverage
    """
    This is the view function for generating our SP metadata
    for SAML authentication. It's meant for helping check the correctness
    of the configuration when setting up SAML, or for obtaining the XML metadata
    if the IdP requires it.
    Taken from https://python-social-auth.readthedocs.io/en/latest/backends/saml.html
    """
    if not saml_auth_enabled():
        return config_error(request, "saml")

    complete_url = reverse("social:complete", args=("saml",))
    saml_backend = load_backend(load_strategy(request), "saml", complete_url)
    metadata, errors = saml_backend.generate_metadata_xml()
    if not errors:
        return HttpResponse(content=metadata, content_type="text/xml")

    return HttpResponseServerError(content=", ".join(errors))
```

[zerver/views/auth.py](https://github.com/zulip/zulip/blob/b7447c202368c7d05ee2c3628782d2f1af5d68f0/zerver/views/auth.py#L1343-L1361) · [More projects using social-auth-app-django →](https://dashboard.exa.ai/playground/search?q=social-auth-app-django%20GitHub%20projects)

**Quickstart**

```python
from django.urls import include, path

urlpatterns = [
    path("", include("social_django.urls", namespace="social")),
]

```

From [django.rst](https://python-social-auth.readthedocs.io/en/latest/configuration/django.html)

### django-otp

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

Adds two-factor authentication with one-time passwords to Django.

- Downloads / mo: 5.7M
- Stars: 629
- Last release: 1.7.5
- License: Unlicense
- Capabilities: [From the django-otp docs](https://django-otp-official.readthedocs.io/)

```sh
pip install django-otp
```

**jazzband/django-two-factor-auth** (1.9K stars)

[jazzband/django-two-factor-auth](https://github.com/jazzband/django-two-factor-auth) 

```python
def done(self, form_list, **kwargs):
    """
    Finish the wizard. Save all forms and redirect.
    """
    # Remove secret key used for QR code generation
    try:
        del self.request.session[self.session_key_name]
    except KeyError:
        pass

    method = self.get_method()
    # TOTPDeviceForm
    if method.code == 'generator':
        form = [form for form in form_list if isinstance(form, TOTPDeviceForm)][0]
        device = form.save()

    # PhoneNumberForm / YubiKeyDeviceForm / EmailForm / WebauthnDeviceValidationForm
    elif method.code in ('call', 'sms', 'yubikey', 'email', 'webauthn'):
        device = self.get_device()
        device.confirmed = True
        device.save()

    django_otp.login(self.request, device)
    return redirect(self.get_success_url())
```

[two_factor/views/core.py](https://github.com/jazzband/django-two-factor-auth/blob/a9c0b2e5d12f2848e646a8af4a251b2afc358e08/two_factor/views/core.py#L532-L555) · [More projects using django-otp →](https://dashboard.exa.ai/playground/search?q=django-otp%20GitHub%20projects)

**Quickstart**

```python
from django.conf import settings

settings.configure(
    SECRET_KEY="example-only",
    INSTALLED_APPS=["django.contrib.auth", "django.contrib.contenttypes", "django_otp", "django_otp.plugins.otp_hotp"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
    USE_TZ=True,
)
import django
django.setup()
from django.core.management import call_command
from django.contrib.auth import get_user_model
from django_otp.plugins.otp_hotp.models import HOTPDevice

call_command("migrate", verbosity=0)
user = get_user_model().objects.create_user(username="example")
device = HOTPDevice.objects.create(user=user, key=b"12345678901234567890".hex(), tolerance=0)
print(device.verify_token(755224))

```

From [models.py](https://raw.githubusercontent.com/django-otp/django-otp/v1.7.5/src/django_otp/plugins/otp_hotp/models.py)

### Flask-JWT-Extended

[GitHub](https://github.com/vimalloc/flask-jwt-extended) · [PyPI](https://pypi.org/project/flask-jwt-extended) · [Docs](https://pypi.org/project/flask-jwt-extended/)

Adds JWT support to Flask.

- Downloads / mo: 5.2M
- Stars: 1.6K
- Last release: 4.7.4
- License: MIT
- Capabilities: [From the Flask-JWT-Extended docs](https://pypi.org/project/flask-jwt-extended/)

```sh
pip install flask-jwt-extended
```

**dpgaspar/Flask-AppBuilder** (5.0K stars)

[dpgaspar/Flask-AppBuilder](https://github.com/dpgaspar/Flask-AppBuilder) 

```python
@expose("/refresh", methods=["POST"])
@jwt_required(refresh=True)
@safe
def refresh(self) -> Response:
    """
        Security endpoint for the refresh token, so we can obtain a new
        token without forcing the user to login again
    ---
    post:
      description: >-
        Use the refresh token to get a new JWT access token
      responses:
        200:
          description: Refresh Successful
          content:
            application/json:
              schema:
                type: object
                properties:
                  access_token:
                    description: A new refreshed access token
                    type: string
        401:
          $ref: '#/components/responses/401'
        500:
          $ref: '#/components/responses/500'
      security:
        - jwt_refresh: []
    """
    resp = {
        API_SECURITY_ACCESS_TOKEN_KEY: create_access_token(
            identity=get_jwt_identity(), fresh=False
        )
    }
    return self.response(200, **resp)
```

[flask_appbuilder/security/api.py](https://github.com/dpgaspar/Flask-AppBuilder/blob/44f3522df563dd8af35c87fcafd59fa2e53b4f90/flask_appbuilder/security/api.py#L123-L157) · [More projects using Flask-JWT-Extended →](https://dashboard.exa.ai/playground/search?q=flask-jwt-extended%20GitHub%20projects)

**Quickstart**

```python
from flask import Flask
from flask_jwt_extended import JWTManager, create_access_token

app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "super-secret"  # Local example only; replace this key.
JWTManager(app)

with app.app_context():
    token = create_access_token(identity="example")
    print(token)

```

From [basic_usage.html](https://flask-jwt-extended.readthedocs.io/en/stable/basic_usage.html)

## FAQ

### Which Python authentication library should I use?

[Flask-Login](#flask-login-library) suits Flask apps that manage their own user sessions. [django-allauth](#django-allauth) suits Django sites that need registration and social sign-in. [Authlib](#authlib) suits apps that act as OAuth or OpenID Connect clients or servers.

### What is django-allauth?

[django-allauth](#django-allauth) provides account registration, email verification, and social sign-in for Django in one package.

### How do I add login to a Flask app?

[Flask-Login](#flask-login-library) manages the signed-in user's session and protects views that require login. Token-based APIs use [Flask-JWT-Extended](#flask-jwt-extended) instead.

### How do I add authentication to FastAPI?

[Authlib](#authlib) integrates with Starlette and FastAPI for OAuth and OpenID Connect sign-in. API routes check tokens through FastAPI security dependencies.

### What is Authlib?

[Authlib](#authlib) builds OAuth and OpenID Connect clients and servers in Python. It integrates with Flask, Django, Starlette, and the requests and HTTPX clients.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python authentication libraries Flask Login Flask Security django allauth FastAPI Users code examples",
    "numResults": 5
  }
}
```

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