Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
5e95ea2
Add Device model
duzumaki Jan 6, 2025
a439a31
Adhere content-type request header to CGI standard
duzumaki Jan 6, 2025
09c7857
Add create device authorization response method
duzumaki Jan 6, 2025
a98c83d
Update the grant type mapping to recognize device code
duzumaki Jan 6, 2025
123b548
Devices that are public should not need basic auth
duzumaki Jan 6, 2025
18317a2
Add device settings
duzumaki Jan 6, 2025
0029583
Create device authorization view
duzumaki Jan 6, 2025
3fe8719
Ensure we import in the views module
duzumaki Jan 6, 2025
84d5f14
Migrations
duzumaki Jan 6, 2025
284fa4a
Add initial stage test
duzumaki Jan 7, 2025
1fc9856
Temp commit: Point oauthlib to master
duzumaki Jan 7, 2025
9f31e23
Add device poll change test
duzumaki Jan 7, 2025
16b9ea1
Add incorrect client id test
duzumaki Jan 7, 2025
1a843c5
Update authors and changelog
duzumaki Jan 7, 2025
6a44ab1
Add the device user code form
duzumaki Jan 14, 2025
793874b
Add approve deny form
duzumaki Jan 14, 2025
96965a9
Update request body validator
duzumaki Jan 14, 2025
1d426ee
Update device imports
duzumaki Jan 14, 2025
54e66ef
Update token endpoint
duzumaki Jan 14, 2025
d7d802e
Prep the tests: Create user_code_generator util
duzumaki Jan 14, 2025
735db9f
Add user code generator to main settings
duzumaki Jan 14, 2025
f94b63d
Add tests to test the whole flow
duzumaki Jan 14, 2025
83e5f7c
Update idp requirements
duzumaki Jan 14, 2025
2d66b40
Add tutotial doc
duzumaki Jan 7, 2025
a924efb
Update idp requirements
duzumaki Jan 24, 2025
02ea665
Ensure the django user sets the oauthlib request user
duzumaki Jan 24, 2025
32a329e
Ensure device token errors are returning 400
duzumaki Jan 29, 2025
14e2619
Add device code to refresh token mapping
duzumaki Jan 31, 2025
571ea33
chore: address documentation notes
dopry May 19, 2025
ed4a2fb
chore: add more details to the tutorial docs
cristiprg May 22, 2025
4e8063f
fix: addressed comments; enhanced preconditions and responses of views
cristiprg May 23, 2025
895ab8c
Use term DeviceGrant over Device
cristiprg Jun 6, 2025
c5f0a80
test: add missing unit test for user_code_generator
cristiprg Jun 11, 2025
bdca7d7
Use latest oauthlib 3.3.0
cristiprg Jun 23, 2025
e89cee6
Use class based views to make them more easily extensible
cristiprg Jun 16, 2025
039b99e
Bugfix: handle missing client_id
cristiprg Aug 13, 2025
4dea003
Increase test coverage
cristiprg Aug 14, 2025
d77193f
Add missing test case in the validor class
cristiprg Aug 18, 2025
c10a471
Remove serialisation methods of DeviceGrant class
cristiprg Aug 18, 2025
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
2 changes: 2 additions & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,15 @@ Bas van Oostveen
Brian Helba
Carl Schwan
Cihad GUNDOGDU
Cristian Prigoana
Daniel Golding
Daniel 'Vector' Kerr
Darrel O'Pry
Dave Burkholder
David Fischer
David Hill
David Smith
David Uzumaki
Dawid Wolski
Diego Garcia
Dominik George
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* #1506 Support for Wildcard Origin and Redirect URIs - Adds a new setting [ALLOW_URL_WILDCARDS](https://django-oauth-toolkit.readthedocs.io/en/latest/settings.html#allow-uri-wildcards). This feature is useful for working with CI service such as cloudflare, netlify, and vercel that offer branch
deployments for development previews and user acceptance testing.
* #1586 Turkish language support added
* #1539 Add device authorization grant support

### Changed
The project is now hosted in the django-oauth organization.
Expand Down
Binary file added docs/_images/application-register-device-code.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/_images/device-approve-deny.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/_images/device-enter-code-displayed.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion docs/tutorial/tutorial.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ Tutorials
tutorial_03
tutorial_04
tutorial_05

tutorial_06
126 changes: 126 additions & 0 deletions docs/tutorial/tutorial_06.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
Part 6 - Device authorization grant flow
====================================================

Scenario
--------
In :doc:`Part 1 <tutorial_01>` you created your own :term:`Authorization Server` and it's running along just fine.
You have devices that your users have, and those users need to authenticate the device against your
:term:`Authorization Server` in order to make the required API calls.

Device Authorization
--------------------
The OAuth 2.0 device authorization grant is designed for Internet
connected devices that either lack a browser to perform a user-agent
based authorization or are input-constrained to the extent that
requiring the user to input text in order to authenticate during the
authorization flow is impractical. It enables OAuth clients on such
devices (like smart TVs, media consoles, digital picture frames, and
printers) to obtain user authorization to access protected resources
by using a user agent on a separate device.

Point your browser to `http://127.0.0.1:8000/o/applications/register/` to create an application.

Fill the form as shown in the screenshot below, and before saving, take note of the ``Client id``.
Make sure the client type is set to "Public." There are cases where a confidential client makes sense,
but generally, it is assumed the device is unable to safely store the client secret.

.. image:: ../_images/application-register-device-code.png
:alt: Device Authorization application registration

Ensure the setting ``OAUTH_DEVICE_VERIFICATION_URI`` is set to a URI you want to return in the
`verification_uri` key in the response. This is what the device will display to the user.

1. Navigate to the tests/app/idp directory:

.. code-block:: sh
cd tests/app/idp
then start the server

.. code-block:: sh
python manage.py runserver
.. _RFC: https://www.rfc-editor.org/rfc/rfc8628
.. _RFC section 3.5: https://datatracker.ietf.org/doc/html/rfc8628#section-3.5

2. To initiate device authorization, send this request (in the real world, the device
makes this request). In `RFC`_ Figure 1, this is step (A).

.. code-block:: sh
curl --location 'http://127.0.0.1:8000/o/device-authorization/' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id={your application client id}'
The OAuth2 provider will return the following response. In `RFC`_ Figure 1, this is step (B).

.. code-block:: json
{
"verification_uri": "http://127.0.0.1:8000/o/device",
"expires_in": 1800,
"user_code": "A32RVADM",
"device_code": "G30j94v0kNfipD4KmGLTWeL4eZnKHm",
"interval": 5
}
In the real world, the device will somehow make the value of the `user_code` available to the user (either on-screen display,
or Bluetooth, NFC, etc.). In `RFC`_ Figure 1, this is step (C).

3. Go to `http://127.0.0.1:8000/o/device` in your browser.

.. image:: ../_images/device-enter-code-displayed.png

Enter the code, and it will redirect you to the device-confirm endpoint. In `RFC`_ Figure 1, this is step (D).

Device-confirm endpoint
-----------------------
4. Device polling occurs concurrently while the user approves or denies the request.

.. image:: ../_images/device-approve-deny.png

Device polling
--------------
Send the following request (in the real world, the device makes this request). In `RFC`_ Figure 1, this is step (E).

.. code-block:: sh
curl --location 'http://localhost:8000/o/token/' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'device_code={the device code from the device-authorization response}' \
--data-urlencode 'client_id={your application client id}' \
--data-urlencode 'grant_type=urn:ietf:params:oauth:grant-type:device_code'
In `RFC`_ Figure 1, there are multiple options for step (F), as per `RFC section 3.5`_. Until the user enters the code
in the browser and approves, the response will be 400:

.. code-block:: json
{"error": "authorization_pending"}
Or if the user has denied the device, the response is 400:

.. code-block:: json
{"error": "access_denied"}
Or if the token has expired, the response is 400:

.. code-block:: json
{"error": "expired_token"}
However, after the user approves, the response will be 200:

.. code-block:: json
{
"access_token": "SkJMgyL432P04nHDPyB63DEAM0nVxk",
"expires_in": 36000,
"token_type": "Bearer",
"scope": "openid",
"refresh_token": "Go6VumurDfFAeCeKrpCKPDtElV77id"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Generated by Django 5.1.5 on 2025-01-24 14:00

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('oauth2_provider', '0012_add_token_checksum'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.AlterField(
model_name='application',
name='authorization_grant_type',
field=models.CharField(choices=[('authorization-code', 'Authorization code'), ('urn:ietf:params:oauth:grant-type:device_code', 'Device Code'), ('implicit', 'Implicit'), ('password', 'Resource owner password-based'), ('client-credentials', 'Client credentials'), ('openid-hybrid', 'OpenID connect hybrid')], max_length=44),
),
migrations.CreateModel(
name='DeviceGrant',
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)),
('device_code', models.CharField(max_length=100, unique=True)),
('user_code', models.CharField(max_length=100)),
('scope', models.CharField(max_length=64, null=True)),
('interval', models.IntegerField(default=5)),
('expires', models.DateTimeField()),
('status', models.CharField(blank=True, choices=[('authorized', 'Authorized'), ('authorization-pending', 'Authorization pending'), ('expired', 'Expired'), ('denied', 'Denied')], default='authorization-pending', max_length=64)),
('client_id', models.CharField(db_index=True, max_length=100)),
('last_checked', models.DateTimeField(auto_now=True)),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='%(app_label)s_%(class)s', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
'swappable': 'OAUTH2_PROVIDER_DEVICE_GRANT_MODEL',
'constraints': [models.UniqueConstraint(fields=('device_code',), name='oauth2_provider_devicegrant_unique_device_code')],
},
),
]
107 changes: 105 additions & 2 deletions oauth2_provider/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
import time
import uuid
from contextlib import suppress
from datetime import timedelta
from dataclasses import dataclass
from datetime import datetime, timedelta
from datetime import timezone as dt_timezone
from typing import Callable, Optional, Union
from urllib.parse import parse_qsl, urlparse

from django.apps import apps
Expand Down Expand Up @@ -86,12 +89,14 @@ class AbstractApplication(models.Model):
)

GRANT_AUTHORIZATION_CODE = "authorization-code"
GRANT_DEVICE_CODE = "urn:ietf:params:oauth:grant-type:device_code"
GRANT_IMPLICIT = "implicit"
GRANT_PASSWORD = "password"
GRANT_CLIENT_CREDENTIALS = "client-credentials"
GRANT_OPENID_HYBRID = "openid-hybrid"
GRANT_TYPES = (
(GRANT_AUTHORIZATION_CODE, _("Authorization code")),
(GRANT_DEVICE_CODE, _("Device Code")),
(GRANT_IMPLICIT, _("Implicit")),
(GRANT_PASSWORD, _("Resource owner password-based")),
(GRANT_CLIENT_CREDENTIALS, _("Client credentials")),
Expand Down Expand Up @@ -127,7 +132,7 @@ class AbstractApplication(models.Model):
default="",
)
client_type = models.CharField(max_length=32, choices=CLIENT_TYPES)
authorization_grant_type = models.CharField(max_length=32, choices=GRANT_TYPES)
authorization_grant_type = models.CharField(max_length=44, choices=GRANT_TYPES)
client_secret = ClientSecretField(
max_length=255,
blank=True,
Expand Down Expand Up @@ -650,11 +655,109 @@ class Meta(AbstractIDToken.Meta):
swappable = "OAUTH2_PROVIDER_ID_TOKEN_MODEL"


class AbstractDeviceGrant(models.Model):
class Meta:
abstract = True
constraints = [
models.UniqueConstraint(
fields=["device_code"],
name="%(app_label)s_%(class)s_unique_device_code",
),
]

AUTHORIZED = "authorized"
AUTHORIZATION_PENDING = "authorization-pending"
EXPIRED = "expired"
DENIED = "denied"

DEVICE_FLOW_STATUS = (
(AUTHORIZED, _("Authorized")),
(AUTHORIZATION_PENDING, _("Authorization pending")),
(EXPIRED, _("Expired")),
(DENIED, _("Denied")),
)

id = models.BigAutoField(primary_key=True)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name="%(app_label)s_%(class)s",
null=True,
blank=True,
on_delete=models.CASCADE,
)
device_code = models.CharField(max_length=100, unique=True)
user_code = models.CharField(max_length=100)
scope = models.CharField(max_length=64, null=True)
interval = models.IntegerField(default=5)
expires = models.DateTimeField()
status = models.CharField(
max_length=64, blank=True, choices=DEVICE_FLOW_STATUS, default=AUTHORIZATION_PENDING
)
client_id = models.CharField(max_length=100, db_index=True)
last_checked = models.DateTimeField(auto_now=True)

def is_expired(self):
"""
Check device flow session expiration and set the status to "expired" if current time
is past the "expires" deadline.
"""
if self.status == self.EXPIRED:
return True

now = datetime.now(tz=dt_timezone.utc)
if now >= self.expires:
self.status = self.EXPIRED
self.save(update_fields=["status"])
return True

return False


class DeviceGrant(AbstractDeviceGrant):
class Meta(AbstractDeviceGrant.Meta):
swappable = "OAUTH2_PROVIDER_DEVICE_GRANT_MODEL"


@dataclass
class DeviceRequest:
# https://datatracker.ietf.org/doc/html/rfc8628#section-3.1
# scope is optional
client_id: str
scope: Optional[str] = None


@dataclass
class DeviceCodeResponse:
verification_uri: str
expires_in: int
user_code: int
device_code: str
interval: int
verification_uri_complete: Optional[Union[str, Callable]] = None


def create_device_grant(device_request: DeviceRequest, device_response: DeviceCodeResponse) -> DeviceGrant:
now = datetime.now(tz=dt_timezone.utc)

return DeviceGrant.objects.create(
client_id=device_request.client_id,
device_code=device_response.device_code,
user_code=device_response.user_code,
scope=device_request.scope,
expires=now + timedelta(seconds=device_response.expires_in),
)


def get_application_model():
"""Return the Application model that is active in this project."""
return apps.get_model(oauth2_settings.APPLICATION_MODEL)


def get_device_grant_model():
"""Return the DeviceGrant model that is active in this project."""
return apps.get_model(oauth2_settings.DEVICE_GRANT_MODEL)


def get_grant_model():
"""Return the Grant model that is active in this project."""
return apps.get_model(oauth2_settings.GRANT_MODEL)
Expand Down
13 changes: 13 additions & 0 deletions oauth2_provider/oauth2_backends.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
from urllib.parse import urlparse, urlunparse

from django.http import HttpRequest
from oauthlib import oauth2
from oauthlib.common import Request as OauthlibRequest
from oauthlib.common import quote, urlencode, urlencoded
Expand Down Expand Up @@ -75,6 +76,8 @@ def extract_headers(self, request):
del headers["wsgi.errors"]
if "HTTP_AUTHORIZATION" in headers:
headers["Authorization"] = headers["HTTP_AUTHORIZATION"]
if "CONTENT_TYPE" in headers:
headers["Content-Type"] = headers["CONTENT_TYPE"]
# Add Access-Control-Allow-Origin header to the token endpoint response for authentication code grant,
# if the origin is allowed by RequestValidator.is_origin_allowed.
# https://github.com/oauthlib/oauthlib/pull/791
Expand Down Expand Up @@ -148,6 +151,16 @@ def create_authorization_response(self, request, scopes, credentials, allow):
except oauth2.OAuth2Error as error:
raise OAuthToolkitError(error=error, redirect_uri=credentials["redirect_uri"])

def create_device_authorization_response(self, request: HttpRequest):
uri, http_method, body, headers = self._extract_params(request)
try:
headers, body, status = self.server.create_device_authorization_response(
uri, http_method, body, headers
)
return headers, body, status
except OAuth2Error as exc:
return exc.headers, exc.json, exc.status_code

def create_token_response(self, request):
"""
A wrapper method that calls create_token_response on `server_class` instance.
Expand Down
Loading
Loading