Metadata-Version: 2.4
Name: django-simple-third-party-jwt
Version: 0.5.0
Summary: Easy to use JWT with 3rd party login.
Home-page: https://github.com/NatLee/django-simple-3rd-party-jwt
Author: Nat Lee
Author-email: natlee.work@gmail.com
Project-URL: Documentation, https://github.com/NatLee/django-simple-3rd-party-jwt
Project-URL: Bug Reports, https://github.com/NatLee/django-simple-3rd-party-jwt/issues
Project-URL: Source Code, https://github.com/NatLee/django-simple-3rd-party-jwt
Keywords: django,jwt,3rd party login,microsoft login,google login
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Build Tools
Classifier: Framework :: Django
Classifier: Framework :: Django :: 4.0
Classifier: Framework :: Django :: 4.1
Classifier: Framework :: Django :: 4.2
Classifier: Framework :: Django :: 5.0
Classifier: Framework :: Django :: 5.1
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Framework :: Django :: 6.1
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: django>=4.0.0
Requires-Dist: djangorestframework
Requires-Dist: djangorestframework-simplejwt>=5.0.0
Requires-Dist: google-auth[requests]
Requires-Dist: msal
Provides-Extra: dev
Requires-Dist: check-manifest; extra == "dev"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license-file
Dynamic: project-url
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/NatLee/django-simple-3rd-party-jwt/main/docs/images/hero-dark.png">
    <img src="https://raw.githubusercontent.com/NatLee/django-simple-3rd-party-jwt/main/docs/images/hero-light.png" alt="Django Simple 3rd Party JWT: the browser signs in with Google (POST /api/auth/google/token) or Microsoft (GET /api/auth/microsoft/signin), your Django site checks the login with the provider, keeps only the VALID_REGISTER_DOMAINS and finds or creates the user, and you get a Simple JWT access/refresh pair back to send as Authorization: Bearer">
  </picture>
</p>

<p align="center">
  <a href="https://github.com/NatLee/django-simple-3rd-party-jwt/actions/workflows/test.yml"><img src="https://github.com/NatLee/django-simple-3rd-party-jwt/actions/workflows/test.yml/badge.svg" alt="Test"></a>
  <a href="https://pypi.org/project/django-simple-third-party-jwt/"><img src="https://img.shields.io/pypi/v/django-simple-third-party-jwt" alt="PyPI"></a>
  <a href="https://pypi.org/project/django-simple-third-party-jwt/"><img src="https://img.shields.io/pypi/pyversions/django-simple-third-party-jwt" alt="Python"></a>
  <a href="https://pypi.org/project/django-simple-third-party-jwt/"><img src="https://img.shields.io/pypi/frameworkversions/django/django-simple-third-party-jwt?label=django" alt="Django"></a>
  <a href="https://github.com/NatLee/django-simple-3rd-party-jwt/blob/main/LICENSE"><img src="https://img.shields.io/github/license/NatLee/django-simple-3rd-party-jwt" alt="License: MIT"></a>
</p>

Let people sign in to your Django site with **Google** or **Microsoft** and hand your
frontend a **JWT** it can send to your API. Add one app and a few settings and you get
login endpoints that check the provider's answer, keep only the e-mail domains you
allow, create the Django user on first login and answer with a
[Simple JWT](https://github.com/jazzband/djangorestframework-simplejwt) access/refresh pair.
No passwords to store, no OAuth plumbing to write.

- **Google**: your page shows Google's sign-in button, then POSTs the credential to `/api/auth/google/token`.
- **Microsoft**: a link to `/api/auth/microsoft/signin`; the user comes back with the tokens in `localStorage`.
- **Your API**: accepts `Authorization: Bearer <access token>` like any Simple JWT project.

## How it works

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/NatLee/django-simple-3rd-party-jwt/main/docs/images/login-flow-dark.png">
    <img src="https://raw.githubusercontent.com/NatLee/django-simple-3rd-party-jwt/main/docs/images/login-flow-light.png" alt="Sequence diagram. Google: the browser opens Google's sign-in popup and gets an ID token (the credential), POSTs it to /api/auth/google/token, your site checks it with Google's keys and your client ID, checks the e-mail domain, finds or creates the user and answers 200 with access and refresh tokens. Microsoft: the browser opens /api/auth/microsoft/signin, is redirected to Microsoft, signs in, comes back to /api/auth/microsoft/callback with a code, your site swaps the code for tokens with MSAL, checks the e-mail domain, finds or creates the user, logs it into the session and answers with a page that saves the JWTs in localStorage and goes to LOGIN_REDIRECT_URL. Then the browser calls your API with Authorization: Bearer and the access token.">
  </picture>
</p>

- **Google** happens in the page: Google's popup hands the browser an ID token (the
  `credential`), the page POSTs it to `/api/auth/google/token`, and your site checks it
  with Google's public keys and your client ID before answering with JSON.
- **Microsoft** happens in redirects: `/api/auth/microsoft/signin` sends the browser to
  Microsoft, Microsoft sends it back to `/api/auth/microsoft/callback` with a code, and your
  site swaps that code for Microsoft tokens (with your client ID and secret). The callback
  answers with a small page that saves the JWTs in `localStorage` and goes on to `LOGIN_REDIRECT_URL`.
- **Both** let in only verified e-mail addresses on the domains listed in
  `VALID_REGISTER_DOMAINS`, find or create the Django user, and hand out a Simple JWT
  access/refresh pair.

Each Google or Microsoft account is linked to a Django user through a small
`SocialAccount` table (`social_account` in the database, also in the Django admin), keyed
by the account's fixed ID (Google's `sub`, Microsoft's tenant and object IDs), so a
returning user gets the same account even after changing their name or address. Any user
model works: the app uses your `AUTH_USER_MODEL`.

## Install

```bash
pip install django-simple-third-party-jwt
```

This also installs Django REST framework, Simple JWT, `google-auth` and `msal`
(Microsoft's auth library). See [supported versions](#supported-versions).

## Quick start

These steps take a Django project to a login page where both buttons work, on
`http://localhost:8000`. Only need one provider? Skip the other one's parts.

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/NatLee/django-simple-3rd-party-jwt/main/docs/images/setup-map-dark.png">
    <img src="https://raw.githubusercontent.com/NatLee/django-simple-3rd-party-jwt/main/docs/images/setup-map-light.png" alt="What goes where. Your project: settings.py adds rest_framework and django_simple_third_party_jwt to INSTALLED_APPS, sets JWT_3RD_PREFIX = &quot;api&quot; and the Google and Microsoft client settings; urls.py includes django_simple_third_party_jwt.urls at the root and serves login.html at /login/; templates/login.html has the Google button and a link to /api/auth/microsoft/signin. Your site on http://localhost:8000 then serves /login/ and the five /api/auth/... routes, and a login gives a Simple JWT access/refresh pair for Authorization: Bearer. At the provider: Google Cloud console, an OAuth client ID of type Web application with http://localhost and http://localhost:8000 as authorized JavaScript origins, whose client ID goes into SOCIAL_GOOGLE_CLIENT_ID; Azure app registration with the redirect URI http://localhost:8000/api/auth/microsoft/callback, whose application (client) ID and client secret value go into SOCIAL_MICROSOFT_CLIENT_ID and SOCIAL_MICROSOFT_CLIENT_SECRET. The site address must match the Google origin and the callback route must match the Azure redirect URI exactly.">
  </picture>
</p>

### 1. Register your site with Google and Microsoft

The buttons only work with credentials of your own. For local testing you need:

- **Google**: an OAuth client ID of type *Web application*, with `http://localhost` and
  `http://localhost:8000` as *Authorized JavaScript origins*.
- **Microsoft**: an Azure app registration with the redirect URI
  `http://localhost:8000/api/auth/microsoft/callback` (platform *Web*), and a client secret.
  For work and school accounts, also switch on the optional claims `email` and `xms_edov`.

Click-by-click instructions are in [Getting credentials](#getting-credentials). The `api` in
the redirect URI is the `JWT_3RD_PREFIX` from the next step; the two have to agree.

### 2. Settings

In `settings.py`, add the app, choose the URL prefix and let your API accept the JWT:

```python
INSTALLED_APPS = [
    # ... Django's defaults, including "django.contrib.sessions"
    "rest_framework",
    "django_simple_third_party_jwt",
]

# The login routes live under /<JWT_3RD_PREFIX>/auth/... ("api" is also the default).
JWT_3RD_PREFIX = "api"

# Only these e-mail domains can sign in.
VALID_REGISTER_DOMAINS = ["gmail.com", "outlook.com", "hotmail.com", "live.com"]

# Let your own API views accept the JWT.
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework_simplejwt.authentication.JWTAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ],
}
```

For Google, add:

```python
SOCIAL_GOOGLE_CLIENT_ID = "<your-client-id>.apps.googleusercontent.com"

# Let Google's sign-in popup talk back to your page, and send the referrer
# when testing on http://localhost (see Google's setup guide, linked below).
SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin-allow-popups"
SECURE_REFERRER_POLICY = "no-referrer-when-downgrade"
```

For Microsoft, add the following, and keep the secret out of your code:

```python
import os

SOCIAL_MICROSOFT_CLIENT_ID = "<your-application-client-id>"
SOCIAL_MICROSOFT_CLIENT_SECRET = os.environ["SOCIAL_MICROSOFT_CLIENT_SECRET"]

# Where the browser goes after a Microsoft login: the page from step 4.
LOGIN_REDIRECT_URL = "/login/"
```

```bash
export SOCIAL_MICROSOFT_CLIENT_SECRET="<your-client-secret-value>"   # before runserver
```

Left one provider out? Without its settings, Google falls back to a shared demo client and
logs a warning. Microsoft has no demo app, so `manage.py check` warns
(`django_simple_third_party_jwt.W002`) and its sign-in link shows a "not set up" page. If
you only use Google, add `"django_simple_third_party_jwt.W002"` to `SILENCED_SYSTEM_CHECKS`.

### 3. URLs

In your project's `urls.py`, include the app **at the root**. The `api/` part comes
from `JWT_3RD_PREFIX`, so don't put it in `path()` as well (that gives `/api/api/auth/...`).
The Simple JWT views let the frontend refresh and check tokens, and the last line serves
the login page from step 4.

```python
from django.urls import include, path
from django.views.generic import TemplateView
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView

urlpatterns = [
    # ...
    path("", include("django_simple_third_party_jwt.urls")),
    path("api/auth/token", TokenObtainPairView.as_view(), name="token_get"),  # optional: username/password login
    path("api/auth/token/refresh", TokenRefreshView.as_view(), name="token_refresh"),
    path("api/auth/token/verify", TokenVerifyView.as_view(), name="token_verify"),
    path("login/", TemplateView.as_view(template_name="login.html"), name="login"),
]
```

That gives you these routes:

| Route | Name | What it does |
|---|---|---|
| `POST /api/auth/google/token` | `google-token` | Google credential in, JWT pair out |
| `POST /api/auth/google/token/session` | `google-token-session` | Same, and also logs the user into the Django session |
| `GET /api/auth/microsoft/signin` | `microsoft-signin` | Sends the browser to Microsoft's sign-in page |
| `GET /api/auth/microsoft/callback` | `microsoft-callback` | Microsoft sends the browser back here; logs in and hands over the JWTs |
| `GET /api/auth/microsoft/signout` | `microsoft-signout` | Forgets the Microsoft token cache, then goes to sign-in |

### 4. Login page

A plain HTML page is enough. Save it as `templates/login.html` next to `manage.py`, and
tell Django to look in that folder: in `settings.py`, set `"DIRS": [BASE_DIR / "templates"]`
in `TEMPLATES`. Google's script turns the `g_id_onload` div into a sign-in button and
calls your function with the credential:

```html
<!doctype html>
<title>Sign in</title>
<script src="https://accounts.google.com/gsi/client" async></script>

<div id="g_id_onload"
     data-client_id="<your-client-id>.apps.googleusercontent.com"
     data-callback="onGoogleCredential"></div>
<div class="g_id_signin" data-type="standard"></div>

<p><a href="/api/auth/microsoft/signin">Sign in with Microsoft</a></p>
<p id="status"></p>

<script>
  async function onGoogleCredential({ credential }) {
    const response = await fetch("/api/auth/google/token", {  // or .../token/session
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ credential }),
    });
    if (!response.ok) {
      console.error("Login refused:", response.status, await response.json());
      return;
    }
    const { access, refresh } = await response.json();
    // The same keys the Microsoft callback page uses by default.
    localStorage.setItem("access_token", access);
    localStorage.setItem("refresh_token", refresh);
    showStatus();
  }

  // Later, call your API with the token:
  function callApi(url) {
    return fetch(url, {
      headers: { Authorization: `Bearer ${localStorage.getItem("access_token")}` },
    });
  }

  // Microsoft comes back to this page (LOGIN_REDIRECT_URL) with the tokens already stored.
  function showStatus() {
    const token = localStorage.getItem("access_token");
    document.getElementById("status").textContent =
      token ? "Signed in. Access token: " + token.slice(0, 24) + "…" : "Not signed in yet.";
  }
  showStatus();
</script>
```

The login endpoints need no CSRF token. In a Django template you can render the client
ID from `settings.SOCIAL_GOOGLE_CLIENT_ID` instead of typing it twice.

### 5. Migrate and run

```bash
python manage.py migrate
python manage.py runserver
```

Run the full `migrate`: the app's own table *and* Django's session table are needed.

Then open <http://localhost:8000/login/>. Use `localhost`, not `127.0.0.1`: Google only
accepts the origins you registered, and the Microsoft redirect URI is built from the
address in your browser.

### 6. Check that it works

Sign in with either button. The page then says `Signed in. Access token: eyJhbGciOi…`
(with Microsoft, after a short "Welcome!" page). To check a token by hand, copy it from
the browser's `localStorage` (developer tools → Application) and ask Simple JWT:

```bash
curl -i -X POST http://localhost:8000/api/auth/token/verify -d "token=<access token>"
```

`200` with `{}` means the token is valid; anything else answers `401` with
`"code": "token_not_valid"`.

Your own views see the signed-in user once the request carries the token. For example,
in a `views.py` next to `urls.py`:

```python
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response


@api_view(["GET"])
@permission_classes([IsAuthenticated])
def me(request):
    return Response({"username": request.user.username, "email": request.user.email})
```

Add `path("api/me", views.me)` to `urlpatterns` (with `from . import views`), then
`callApi("/api/me")` in the page, or
`curl -H "Authorization: Bearer <access token>" http://localhost:8000/api/me`, answers
with the user. Without the token it is `401`.

What the Google endpoint answers:

| Situation | Status | Body |
|---|---|---|
| Signed in | `200` | `{"access": "...", "refresh": "...", "access_token": "...", "refresh_token": "..."}` (two names for the same pair) |
| No `credential` in the request | `400` | `{"credential": ["This field is required."]}` |
| E-mail domain not in `VALID_REGISTER_DOMAINS` | `401` | `{"status": "error", "detail": "This email is invalid."}` |
| Google does not accept the credential (malformed, expired, issued for another client ID) | `401` | `{"status": "error", "detail": "Google did not accept the credential: <reason>"}` |
| Google has not verified the e-mail address (`email_verified`) | `401` | `{"status": "error", "detail": "Google has not verified this e-mail address."}` |

After a Microsoft login, the callback page shows a short "Welcome!" and redirects to
`LOGIN_REDIRECT_URL` after a few seconds, with the tokens already in `localStorage`.
The user is also logged into the Django session.
If the domain is not allowed, it says so in red and stores nothing.

## Troubleshooting

| What you see | What to do |
|---|---|
| Warning `django_simple_third_party_jwt.W001` at start-up | `JWT_3RD_PREFIX` has a `/` at one end. It is ignored, so the routes are at `/api/auth/...`; write `"api"` to silence the warning. Coming from 0.3.2 or earlier? See [Upgrading](#from-032-or-earlier). |
| `KeyError: 'SOCIAL_MICROSOFT_CLIENT_SECRET'` at start-up | Export the variable before `runserver`, or leave the Microsoft block out. |
| 404 at `/api/api/auth/...` | You included the app under `path("api/", ...)`. Include it at the root, `path("", ...)`. |
| `no such table: django_session` (or `social_account`), or `NOT NULL constraint failed: auth_user.last_login` | The database is not fully migrated. Run the full `python manage.py migrate`, not just this app. |
| The Google button reports that the origin is not allowed | Add the page's exact origin (scheme, host and port) to the client's *Authorized JavaScript origins*, and open the page at that address. |
| The Google endpoint answers `401` "This email is invalid." | The address's domain is not in `VALID_REGISTER_DOMAINS`. |
| The Google endpoint answers `401` "Google did not accept the credential: …" | The reason follows the colon. Often `SOCIAL_GOOGLE_CLIENT_ID` is not the client ID in your page ("issued for another client ID"), or the credential expired. |
| The Google endpoint answers `401` "Google has not verified this e-mail address." | The Google account's address is not verified. The user has to verify it with Google first. |
| Microsoft shows an `AADSTS50011` redirect URI error | Register exactly the redirect URI the error shows (usually `http://localhost:8000/api/auth/microsoft/callback`), and browse the site at that host. |
| The callback page says "Something went wrong while signing in with Microsoft. Please try again." | The server log has Microsoft's reason. `invalid_client` with `AADSTS7000215` means `SOCIAL_MICROSOFT_CLIENT_SECRET` holds the secret's ID instead of its value, or an expired secret. (Up to 0.3.2 the log only says `'access_token'`.) |
| The callback page says "Sorry, this account is not allowed to sign in here." | The address's domain is not in `VALID_REGISTER_DOMAINS`. |
| The callback page says "Sorry, Microsoft has not confirmed an e-mail address for this account." | A work or school account: switch on the optional claims `email` and `xms_edov` (see [Getting credentials](#getting-credentials)). Or the account has no e-mail address, such as one that signs in with a phone number. |
| Warning `django_simple_third_party_jwt.W002` at start-up, or the page "Microsoft sign-in is not set up on this site." | Set `SOCIAL_MICROSOFT_CLIENT_ID` and `SOCIAL_MICROSOFT_CLIENT_SECRET`. Only using Google? Silence the warning with `SILENCED_SYSTEM_CHECKS`. |
| The Google endpoint answers `401` "Another account already uses this e-mail address. …" (or the Microsoft page says so) | Your user model logs in with the e-mail address, and a user who never signed in through Google or Microsoft already has it. The app does not merge accounts by address. If the sign-in really is that user's, [link it by hand](#linking-a-sign-in-to-an-existing-account). |

### Linking a sign-in to an existing account

When your user model logs in with the e-mail address, a Google or Microsoft sign-in whose
address another user already has is refused. The person sees "Another account already uses
this e-mail address. Sign in to that account the usual way, or ask the site's administrator to
link your Google or Microsoft sign-in to it." The server log says which sign-in collided with
which user, for example:

```text
[AUTH][GOOGLE] Not signing in google account [109876543210987654321]: its address `alice@example.com`
belongs to user pk=42 (alice@example.com), who is not linked to it. To link them, add a SocialAccount
for that user with provider 'google' and unique ID '109876543210987654321' ...
```

Make sure the sign-in belongs to that person (for example, they asked you), because linking it
gives them that account. Then:

1. In the Django admin, open the `SocialAccount` list (shown as *第三方登入（3rd party login）*)
   and choose **Add**.
2. **User**: the user from the log (`pk=42` above). **Provider**: `google` or `microsoft`.
   **Unique ID**: the ID in square brackets in the log. For Google that is the account's `sub`,
   for Microsoft `<tenant ID>/<object ID>`.
3. Save. The next time the person signs in with that Google or Microsoft account, they land in
   the existing user. The unique ID cannot be edited after saving; delete the row and add a new
   one to correct it.

## Upgrading

### From 0.4.0

Check these first if you use Microsoft sign-in:

- **Microsoft accounts are identified by their tenant and object IDs** (`tid` and `oid`), not by
  `preferred_username`, which the account's owner can change. Existing users keep their
  accounts: on their first sign-in after the upgrade, the app finds their record through the
  verified e-mail address (the old records were keyed by that address) and keys it by the IDs
  from then on. A user whose verified address differs from their old `preferred_username` gets
  a new account instead; move their `SocialAccount` row in the admin, or delete it and
  [link the sign-in by hand](#linking-a-sign-in-to-an-existing-account).
- **The allowed domain is checked on an e-mail address Microsoft vouches for.** Personal
  accounts work as they are. For work and school accounts, switch on the optional claims
  `email` and `xms_edov` (*Token configuration* in the app registration); without them those
  sign-ins are refused with "Sorry, Microsoft has not confirmed an e-mail address for this
  account.".
- **The sign-in asks for the `email` permission** as well, so users may see a consent prompt
  once.
- **There are no Microsoft demo credentials any more** (the demo app's secret was public). Set
  `SOCIAL_MICROSOFT_CLIENT_ID` and `SOCIAL_MICROSOFT_CLIENT_SECRET`; `manage.py check`
  warns (`W002`) until you do.

Also in this release:

- The Google endpoint answers `401` with the reason, instead of `500` "Something went wrong :(", when Google does not accept the credential. If your frontend looks for a 500, look for the 401 (or just `!response.ok`).
- Google accounts whose address Google has not verified (`email_verified`) are refused with `401` "Google has not verified this e-mail address.".
- `JWT_3RD_PREFIX` is optional now, with the default `"api"`. Nothing to change if you set it.
- Custom user models (`AUTH_USER_MODEL`) work. A new user's login name is the e-mail's local
  part, or the whole address if your model logs in with it. Projects on Django's built-in
  `User` see no change and get no new migration.
- The Microsoft callback no longer fetches the Microsoft Graph profile (nothing used it), and
  `django_simple_third_party_jwt.views.microsoft.utils` is gone:

  | 0.4.0 import | Now |
  |---|---|
  | `views.microsoft.utils.get_user`, `views.microsoft.utils.graph_url` | Removed. Call Microsoft Graph yourself with a token from `msal_helpers.get_token()`. |
  | `views.microsoft.utils.callback_url` | `views.microsoft.msal_helpers.callback_url` |

### From 0.3.2 or earlier

Only projects whose `JWT_3RD_PREFIX` starts or ends with a `/` (`"/api"`, `"api/"`,
`"/api/"`) or is `"/"` or `""` are affected. With `JWT_3RD_PREFIX = "api"` nothing changes.

0.3.2 and earlier kept that slash, so the routes and the Microsoft redirect URI ended up at
odd addresses. Now the slash is ignored and an empty prefix means "no prefix":

| `JWT_3RD_PREFIX` | Google token route, 0.3.2 | Now | Microsoft redirect URI, 0.3.2 | Now |
|---|---|---|---|---|
| `"api/"` | `/api//auth/google/token` | `/api/auth/google/token` | `<site>/api//auth/microsoft/callback` | `<site>/api/auth/microsoft/callback` |
| `"/api"` | `/%2Fapi/auth/google/token` | `/api/auth/google/token` | `<site>//api/auth/microsoft/callback` | `<site>/api/auth/microsoft/callback` |
| `""` | `/%2Fauth/google/token` | `/auth/google/token` | `<site>//auth/microsoft/callback` | `<site>/auth/microsoft/callback` |

If yours is one of them:

1. In Azure (*App registrations* → your app → *Authentication*), add the new redirect URI.
   Until you do, Microsoft answers `AADSTS50011` (redirect URI mismatch).
2. If your frontend has the old address typed in (with the `//` or `%2F`), change it.
   Links built with `{% url %}` or `reverse()` follow by themselves.
3. Google needs nothing: its *Authorized JavaScript origins* contain no path.
4. Optional: drop the slash from the setting. Until then, `manage.py check` shows the
   warning `django_simple_third_party_jwt.W001` with the new addresses.

The Microsoft callback page also has clearer messages now: "Sorry, this account is not
allowed to sign in here." and "Something went wrong while signing in with Microsoft.
Please try again." If your code or tests look for the old wording, update them.

### From 0.3.0: imports that moved

0.3.1 reorganised the modules and did not keep the old import paths. If you import from the
package (most projects only include its URLs, which did not change), use the new paths:

| 0.3.0 import | Now |
|---|---|
| `django_simple_third_party_jwt.views.google.token_login.GoogleLogin` | `django_simple_third_party_jwt.views.google.GoogleLogin` |
| `django_simple_third_party_jwt.views.google.session_login.GoogleLoginSession` | `django_simple_third_party_jwt.views.google.GoogleLoginSession` |
| `django_simple_third_party_jwt.serializers.GoogleLoginSerializer` | `django_simple_third_party_jwt.serilizers.GoogleLoginSerializer` |
| `django_simple_third_party_jwt.serializers.UserSerializer` | Removed. Write a `ModelSerializer` for your user model. |
| `get_msal_app`, `get_sign_in_flow`, `get_token_from_code`, `get_token`, `load_cache`, `save_cache`, `remove_user_and_token`, `settings` and `callback_url` from `django_simple_third_party_jwt.views.microsoft` | The same names in `django_simple_third_party_jwt.views.microsoft.msal_helpers` |
| `get_user` and `graph_url` from `django_simple_third_party_jwt.views.microsoft` | Removed (see [From 0.4.0](#from-040)). |
| `initialize_context` from `django_simple_third_party_jwt.views.microsoft` | Removed. |
| `sign_in`, `sign_out` and `callback` from `django_simple_third_party_jwt.views.microsoft` | Unchanged. |

## Settings reference

| Setting | Required | Default | What it does |
|---|---|---|---|
| `JWT_3RD_PREFIX` | No | `"api"` | URL prefix for every route: `/<prefix>/auth/...`. A `/` at either end is ignored (`"/api/"` means `"api"`), and `""` puts the routes at `/auth/...`. Also part of the Microsoft redirect URI. |
| `SOCIAL_GOOGLE_CLIENT_ID` | For Google | a shared demo client, with a warning | Your Google OAuth client ID. |
| `SOCIAL_MICROSOFT_CLIENT_ID` | For Microsoft | none: `manage.py check` warns (`W002`) | The *Application (client) ID* of your Azure app. |
| `SOCIAL_MICROSOFT_CLIENT_SECRET` | For Microsoft | none: `manage.py check` warns (`W002`) | A client secret *value* of that app. Load it from the environment. |
| `VALID_REGISTER_DOMAINS` | No | `["gmail.com", "outlook.com", "hotmail.com", "live.com"]` | Only addresses on these domains can sign in, new and returning users alike. Google: the token's `email`, which Google must have verified. Microsoft: the `email` claim, for personal accounts or with `xms_edov` = true. |
| `LOGIN_REDIRECT_URL` | No | Django's default, `/accounts/profile/` | Where the Microsoft callback page sends the browser. |
| `MICROSOFT_JWT_REDIRECT_ACCESS_TOKEN_KEY` | No | `"access_token"` | `localStorage` key the Microsoft callback page stores the access token under. |
| `MICROSOFT_JWT_REDIRECT_REFRESH_TOKEN_KEY` | No | `"refresh_token"` | Same, for the refresh token. |

Good to know:

- The app reads these settings once, at start-up. Changing them at runtime (for example
  with `override_settings` in your tests) does not reach it.
- Don't ship with the demo Google client ID. It belongs to the package author, is public,
  and is meant for trying things out locally. The app logs a warning at start-up while
  you use it. Microsoft has no demo app.
- Token lifetimes and signing are Simple JWT's job: set them in
  [`SIMPLE_JWT`](https://django-rest-framework-simplejwt.readthedocs.io/en/latest/settings.html).
- Frontend on another origin? Add [django-cors-headers](https://github.com/adamchainz/django-cors-headers).
- Behind a reverse proxy, make sure `request.build_absolute_uri()` sees the public scheme
  and host (`SECURE_PROXY_SSL_HEADER`, `USE_X_FORWARDED_HOST`). The Microsoft redirect URI
  is built from it.
- The app works with your `AUTH_USER_MODEL`. A new user's login name is the e-mail's local
  part (or a random one if that is taken), or the whole address if your model logs in with
  it. In that case an address another user already has refuses the sign-in.

## Getting credentials

<details>
<summary><b>Google: client ID</b></summary>

1. Open [Google Cloud console → APIs & Services → Credentials](https://console.cloud.google.com/apis/credentials)
   and pick or create a project. If asked, set up the OAuth consent screen first.
2. **Create credentials → OAuth client ID**, application type **Web application**.
3. Under **Authorized JavaScript origins** add every origin that shows the button.
   For local work add both `http://localhost` and `http://localhost:8000`.
4. Create it and copy the **Client ID** (`....apps.googleusercontent.com`) into
   `SOCIAL_GOOGLE_CLIENT_ID`. The client secret is not needed.

More in Google's guide: [Get your Google API client ID](https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid).

</details>

<details>
<summary><b>Microsoft: client ID and secret</b></summary>

1. Open [Azure portal → Microsoft Entra ID → App registrations](https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/RegisteredApps)
   and choose **New registration**.
2. **Supported account types**: *Accounts in any organizational directory and personal
   Microsoft accounts*. The app signs in through the `common` endpoint, which serves both.
3. **Redirect URI**: platform **Web**, value
   `http://localhost:8000/api/auth/microsoft/callback`, i.e.
   `<site root>/<JWT_3RD_PREFIX>/auth/microsoft/callback`. Add your production URL too.
4. On the app's **Overview** page, copy the **Application (client) ID** into
   `SOCIAL_MICROSOFT_CLIENT_ID`.
5. **Certificates & secrets → New client secret**. Copy the **Value** column right away
   (Azure shows it once; the *Secret ID* is something else) and put it in the
   `SOCIAL_MICROSOFT_CLIENT_SECRET` environment variable.
6. **API permissions** already lists Microsoft Graph `User.Read`. The sign-in also asks for
   `email` (*View users' email address*), so users may see a consent prompt for it once.
7. Work and school accounts only: **Token configuration → Add optional claim → ID**, tick
   `email` and `xms_edov`. The app checks the allowed domain on that address, and only
   when `xms_edov` says the domain's owner is verified. Personal Microsoft accounts need
   nothing here.

</details>

## Example project

[`example/`](https://github.com/NatLee/django-simple-3rd-party-jwt/tree/main/example) is
a small site with a dev dashboard where you can try both logins and see the tokens,
plus Swagger and the admin.

```bash
git clone https://github.com/NatLee/django-simple-3rd-party-jwt
cd django-simple-3rd-party-jwt/example/django_simple_third_party_jwt_example
pip install -r requirements.txt
python manage.py migrate
python manage.py runserver 0.0.0.0:8000
```

Open <http://localhost:8000/api/__hidden_dev_dashboard/>. Other pages:
`/api/__hidden_swagger/`, `/api/__hidden_redoc/` and `/api/__hidden_admin/`
(`python manage.py createsuperuser` first).

![The example's dev dashboard](https://raw.githubusercontent.com/NatLee/django-simple-3rd-party-jwt/main/docs/images/example-dashboard.png)

Google uses the shared demo client unless you export your own; Microsoft needs your own:

```bash
export SOCIAL_GOOGLE_CLIENT_ID="<your-client-id>.apps.googleusercontent.com"
export SOCIAL_MICROSOFT_CLIENT_ID="<your-application-client-id>"
export SOCIAL_MICROSOFT_CLIENT_SECRET="<your-client-secret-value>"
```

For a fuller playground, see
[django-simple-3rd-party-jwt-dev-dashboard](https://github.com/NatLee/django-simple-3rd-party-jwt-dev-dashboard),
a reusable dashboard app built on this package.

## Supported versions

Every combination below runs the test suite in CI:

| Django | Python |
|---|---|
| 4.0 | 3.8 – 3.10 |
| 4.1 | 3.8 – 3.11 |
| 4.2 | 3.8 – 3.12 |
| 5.0 | 3.10 – 3.12 |
| 5.1 | 3.10 – 3.13 |
| 5.2 | 3.10 – 3.14 |
| 6.0, 6.1 | 3.12 – 3.14 |

## Development

```bash
git clone https://github.com/NatLee/django-simple-3rd-party-jwt
cd django-simple-3rd-party-jwt
pip install -e . pytest
pytest tests
```

The tests mock Google and Microsoft, so they need no credentials and no network.
To run the same matrix as CI, use [tox](https://tox.wiki/):

```bash
pip install tox
tox run -f py312     # every supported Django version on Python 3.12
tox run -e package   # check-manifest, build the sdist and wheel, twine check
```

`dev-reinstall.sh` (or `dev-reinstall.ps1` on Windows) builds the sdist and installs it,
which is a quick way to check what a release would contain.

Releases are published to PyPI by GitHub Actions when a GitHub release is created.

## License

[MIT](https://github.com/NatLee/django-simple-3rd-party-jwt/blob/main/LICENSE)
