-
-
Notifications
You must be signed in to change notification settings - Fork 801
Add device authorization grant (device code flow - rfc 8628) #1539
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from 29 commits
cb74933
963fd76
7976ea1
8307494
fed683d
0826ad4
a008ae7
3799dd2
4013d8e
7462112
0e721a5
46eed3b
eac4329
e83a3cd
bb6deec
01fe93c
6306365
1a027d9
1f1e9b0
0918cf4
377d12e
5ff24c8
216ec65
2e64efb
9de753e
81b7710
bfd67a3
c1cb26f
223f991
6dda42b
b666a8f
c61a4eb
ed507c3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,4 +9,4 @@ Tutorials | |
tutorial_03 | ||
tutorial_04 | ||
tutorial_05 | ||
|
||
tutorial_06 |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
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 | ||
|
||
To initiate device authorization, send this request: | ||
|
||
.. 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: | ||
|
||
.. code-block:: json | ||
|
||
{ | ||
"verification_uri": "http://127.0.0.1:8000/o/device", | ||
"expires_in": 1800, | ||
"user_code": "A32RVADM", | ||
"device_code": "G30j94v0kNfipD4KmGLTWeL4eZnKHm", | ||
"interval": 5 | ||
} | ||
|
||
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. | ||
|
||
Device-confirm endpoint | ||
----------------------- | ||
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): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. worth adding another section here with the response before the user accepted? {"error": "authorization_pending"} There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Would this be to demonstrate the alternative response? Would the suggestion here be to add something like if you send this request and the user hasn't yet accepted then you get response ... if the user has accepted you will get the response ... ? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. yup, exactly. Just for completeness |
||
|
||
.. 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\'s client id}' \ | ||
--data-urlencode 'grant_type=urn:ietf:params:oauth:grant-type:device_code' | ||
|
||
The response will be similar to this: | ||
|
||
.. 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='Device', | ||
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_MODEL', | ||
'constraints': [models.UniqueConstraint(fields=('device_code',), name='oauth2_provider_device_unique_device_code')], | ||
}, | ||
), | ||
] |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 | ||
|
@@ -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")), | ||
|
@@ -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, | ||
|
@@ -650,11 +655,110 @@ class Meta(AbstractIDToken.Meta): | |
swappable = "OAUTH2_PROVIDER_ID_TOKEN_MODEL" | ||
|
||
|
||
class AbstractDevice(models.Model): | ||
dopry marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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. | ||
""" | ||
now = datetime.now(tz=dt_timezone.utc) | ||
return now >= self.expires | ||
|
||
|
||
class DeviceManager(models.Manager): | ||
def get_by_natural_key(self, client_id, device_code, user_code): | ||
return self.get(client_id=client_id, device_code=device_code, user_code=user_code) | ||
|
||
|
||
class Device(AbstractDevice): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Likewise maybe There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's not the grant, it's the model that represents the device during the flow's session, There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In the context of I think this very much is the Grant. Note that most of the fields are the same, scope, client_id, expiration, etc. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This seems to be what I'm saying as well. Because it represents the device session and uses the device grant in that session. Am I misunderstanding grant in Oauth2? I define it as a single object that is of some type but doesn't have anything to do with state/session The
While There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would like to see the language around this resolved a bit... If this is in fact a grant session we should name it as such. I'm not a big fan of the bare Device here. To my thinking the device is just that, the physical device and this isn't strictly a representation of the physical device itself, but the relation between the device, a particular user, and the authorization state of the device relative to the user. Device's can have many users, such as public kiosks, or shared devices in homes, phones/tablets with multiple profile in corporate settings, etc. All that to say, Let's be more specific than device here. If we look at the other grants.... I think within the scope of DOT, @danlamanna may have the more consistent interpretation. per oauth2_provider/models.py:302
While I think @duzumaki is correct in a wider context and DOT's current 'AbstractGrant` is too tightly coupled to the AuthoizationCode Grant, and could be further generalized, and possible better named as a GrantSession, it is used to track the sessions details that culminate in the token exchange. The use of a Grant suffix also seems to maintain consistency with the relative relationships of the models in DOT with the grant types in OAuthLib, where DOT's models hold the information returned via the OAuthLib Grant classes. Here I favor consistency over correctness, and would strongly lean toward DeviceGrant in place of Device. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Also agreed that consistency is often just more practical. I've updated to |
||
objects = DeviceManager() | ||
|
||
class Meta(AbstractDevice.Meta): | ||
swappable = "OAUTH2_PROVIDER_DEVICE_MODEL" | ||
|
||
def natural_key(self): | ||
return (self.client_id, self.device_code, self.user_code) | ||
|
||
|
||
@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 | ||
duzumaki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
expires_in: int | ||
user_code: int | ||
device_code: str | ||
interval: int | ||
verification_uri_complete: Optional[Union[str, Callable]] = None | ||
|
||
|
||
def create_device(device_request: DeviceRequest, device_response: DeviceCodeResponse) -> Device: | ||
now = datetime.now(tz=dt_timezone.utc) | ||
|
||
return Device.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_model(): | ||
"""Return the Device model that is active in this project.""" | ||
return apps.get_model(oauth2_settings.DEVICE_MODEL) | ||
|
||
|
||
def get_grant_model(): | ||
"""Return the Grant model that is active in this project.""" | ||
return apps.get_model(oauth2_settings.GRANT_MODEL) | ||
|
Uh oh!
There was an error while loading. Please reload this page.