authentik.providers.oauth2.tests.test_device_flow

Device flow end-to-end tests

  1"""Device flow end-to-end tests"""
  2
  3from json import loads
  4
  5from django.urls import reverse
  6from rest_framework.test import APIClient
  7
  8from authentik.blueprints.tests import apply_blueprint
  9from authentik.common.oauth.constants import (
 10    GRANT_TYPE_DEVICE_CODE,
 11    SCOPE_OPENID,
 12    SCOPE_OPENID_EMAIL,
 13)
 14from authentik.core.models import Application
 15from authentik.core.tests.utils import create_test_admin_user, create_test_brand, create_test_flow
 16from authentik.events.models import Event, EventAction
 17from authentik.events.signals import get_login_event
 18from authentik.lib.generators import generate_id
 19from authentik.providers.oauth2.models import (
 20    AccessToken,
 21    DeviceToken,
 22    GrantType,
 23    OAuth2Provider,
 24    ScopeMapping,
 25)
 26from authentik.providers.oauth2.tests.utils import OAuthTestCase
 27
 28
 29class TestOAuth2DeviceFlow(OAuthTestCase):
 30    """Walk the whole device code flow: back channel, user code entry, finish stage,
 31    token exchange. Nothing else in the suite executes OAuthDeviceCodeFinishStage."""
 32
 33    @apply_blueprint("system/providers-oauth2.yaml")
 34    def setUp(self) -> None:
 35        super().setUp()
 36        self.provider = OAuth2Provider.objects.create(
 37            name=generate_id(),
 38            client_id=generate_id(),
 39            authorization_flow=create_test_flow(),
 40            signing_key=self.keypair,
 41            grant_types=[GrantType.DEVICE_CODE],
 42        )
 43        self.provider.property_mappings.set(ScopeMapping.objects.all())
 44        self.application = Application.objects.create(
 45            name=generate_id(),
 46            slug=generate_id(),
 47            provider=self.provider,
 48        )
 49        self.device_flow = create_test_flow()
 50        self.brand = create_test_brand(flow_device_code=self.device_flow)
 51        self.user = create_test_admin_user()
 52        # A single client for the whole user-facing walk: the flow plan lives in the session,
 53        # so splitting the walk across clients would lose it.
 54        self.user_client = APIClient()
 55        self.user_client.force_login(self.user)
 56
 57    def request_device_code(self, scope: str = f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL}") -> dict:
 58        """Run the back channel and return the device authorization response"""
 59        res = self.client.post(
 60            reverse("authentik_providers_oauth2:device"),
 61            data={
 62                "client_id": self.provider.client_id,
 63                "scope": scope,
 64            },
 65        )
 66        self.assertEqual(res.status_code, 200)
 67        return loads(res.content.decode())
 68
 69    def exchange(self, device_code: str):
 70        """Poll the token endpoint for the given device code"""
 71        return self.client.post(
 72            reverse("authentik_providers_oauth2:token"),
 73            data={
 74                "client_id": self.provider.client_id,
 75                "client_secret": self.provider.client_secret,
 76                "grant_type": GRANT_TYPE_DEVICE_CODE,
 77                "device_code": device_code,
 78            },
 79        )
 80
 81    def authorize_via_query_param(self, device: dict):
 82        """Follow verification_uri_complete and run the resulting flow up to the finish stage"""
 83        res = self.user_client.get(device["verification_uri_complete"])
 84        self.assertEqual(res.status_code, 302)
 85        self.assertIn(self.provider.authorization_flow.slug, res.url)
 86        res = self.user_client.get(
 87            reverse(
 88                "authentik_api:flow-executor",
 89                kwargs={"flow_slug": self.provider.authorization_flow.slug},
 90            ),
 91        )
 92        self.assertEqual(res.status_code, 200)
 93        self.assertEqual(
 94            loads(res.content.decode())["component"],
 95            "ak-provider-oauth2-device-code-finish",
 96        )
 97        return res
 98
 99    def test_device_flow_end_to_end(self):
100        """Full flow: back channel, authorize via query param, exchange the code"""
101        device = self.request_device_code()
102        token = DeviceToken.objects.filter(device_code=device["device_code"]).first()
103        self.assertIsNotNone(token)
104        self.assertIsNone(token.user)
105
106        # Nothing has authorized the code yet
107        res = self.exchange(device["device_code"])
108        self.assertEqual(res.status_code, 400)
109        self.assertEqual(loads(res.content.decode())["error"], "authorization_pending")
110
111        self.authorize_via_query_param(device)
112
113        token.refresh_from_db()
114        self.assertEqual(token.user, self.user)
115
116        # Acknowledge the finish challenge, which completes the flow
117        res = self.user_client.post(
118            reverse(
119                "authentik_api:flow-executor",
120                kwargs={"flow_slug": self.provider.authorization_flow.slug},
121            ),
122            data={"component": "ak-provider-oauth2-device-code-finish"},
123        )
124        self.assertEqual(res.status_code, 200)
125        self.assertEqual(loads(res.content.decode())["component"], "xak-flow-redirect")
126
127        # The device can now exchange its code
128        res = self.exchange(device["device_code"])
129        self.assertEqual(res.status_code, 200)
130        body = loads(res.content.decode())
131        access_token = AccessToken.objects.filter(token=body["access_token"]).first()
132        self.assertIsNotNone(access_token)
133        self.assertEqual(access_token.user, self.user)
134        self.assertSetEqual(set(access_token.scope), {SCOPE_OPENID, SCOPE_OPENID_EMAIL})
135        # Device code is single-use
136        self.assertFalse(
137            DeviceToken.objects.including_expired()
138            .filter(device_code=device["device_code"])
139            .exists()
140        )
141
142    def test_device_flow_end_to_end_code_entry(self):
143        """Full flow, but the user types the code into the brand's device flow"""
144        device = self.request_device_code()
145
146        res = self.user_client.get(reverse("authentik_providers_oauth2_root:device-login"))
147        self.assertEqual(res.status_code, 302)
148        self.assertIn(self.device_flow.slug, res.url)
149
150        executor = reverse(
151            "authentik_api:flow-executor",
152            kwargs={"flow_slug": self.device_flow.slug},
153        )
154        res = self.user_client.get(executor)
155        self.assertEqual(res.status_code, 200)
156        self.assertEqual(loads(res.content.decode())["component"], "ak-provider-oauth2-device-code")
157
158        res = self.user_client.post(
159            executor,
160            data={
161                "component": "ak-provider-oauth2-device-code",
162                "code": device["user_code"],
163            },
164        )
165        self.assertEqual(res.status_code, 200)
166        body = loads(res.content.decode())
167        self.assertEqual(body["component"], "xak-flow-redirect")
168        self.assertIn(self.provider.authorization_flow.slug, body["to"])
169
170        res = self.user_client.get(
171            reverse(
172                "authentik_api:flow-executor",
173                kwargs={"flow_slug": self.provider.authorization_flow.slug},
174            ),
175        )
176        self.assertEqual(res.status_code, 200)
177        self.assertEqual(
178            loads(res.content.decode())["component"],
179            "ak-provider-oauth2-device-code-finish",
180        )
181
182        token = DeviceToken.objects.filter(device_code=device["device_code"]).first()
183        self.assertEqual(token.user, self.user)
184        self.assertTrue(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists())
185
186    def test_authorize_application_event_context(self):
187        """The finish stage logs an application authorization, same shape as authorize.py"""
188        device = self.request_device_code()
189        self.assertFalse(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists())
190
191        self.authorize_via_query_param(device)
192
193        event = Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).first()
194        self.assertIsNotNone(event)
195        self.assertEqual(event.context["authorized_application"]["name"], self.application.name)
196        self.assertEqual(event.context["authorized_application"]["pk"], self.application.pk.hex)
197        self.assertEqual(event.context["flow"], self.provider.authorization_flow.pk.hex)
198        self.assertSetEqual(
199            set(event.context["scopes"].split()), {SCOPE_OPENID, SCOPE_OPENID_EMAIL}
200        )
201        self.assertEqual(event.user["username"], self.user.username)
202
203    def test_finish_stage_binds_session(self):
204        """The finish stage binds the user's session, which the access token inherits"""
205        device = self.request_device_code()
206        self.authorize_via_query_param(device)
207
208        token = DeviceToken.objects.filter(device_code=device["device_code"]).first()
209        self.assertIsNotNone(token.session)
210        self.assertEqual(token.session.user, self.user)
211
212        res = self.exchange(device["device_code"])
213        self.assertEqual(res.status_code, 200)
214        access_token = AccessToken.objects.filter(
215            token=loads(res.content.decode())["access_token"]
216        ).first()
217        self.assertIsNotNone(access_token.session)
218        self.assertEqual(access_token.session.session_id, token.session.session_id)
219
220    def test_finish_stage_auth_time_from_login_event(self):
221        """With a session bound, auth_time comes from the login event instead of now()"""
222        device = self.request_device_code()
223        self.authorize_via_query_param(device)
224
225        token = DeviceToken.objects.filter(device_code=device["device_code"]).first()
226        login_event = get_login_event(token.session)
227        self.assertIsNotNone(login_event)
228
229        res = self.exchange(device["device_code"])
230        self.assertEqual(res.status_code, 200)
231        access_token = AccessToken.objects.filter(
232            token=loads(res.content.decode())["access_token"]
233        ).first()
234        self.assertEqual(access_token.auth_time, login_event.created)
class TestOAuth2DeviceFlow(authentik.providers.oauth2.tests.utils.OAuthTestCase):
 30class TestOAuth2DeviceFlow(OAuthTestCase):
 31    """Walk the whole device code flow: back channel, user code entry, finish stage,
 32    token exchange. Nothing else in the suite executes OAuthDeviceCodeFinishStage."""
 33
 34    @apply_blueprint("system/providers-oauth2.yaml")
 35    def setUp(self) -> None:
 36        super().setUp()
 37        self.provider = OAuth2Provider.objects.create(
 38            name=generate_id(),
 39            client_id=generate_id(),
 40            authorization_flow=create_test_flow(),
 41            signing_key=self.keypair,
 42            grant_types=[GrantType.DEVICE_CODE],
 43        )
 44        self.provider.property_mappings.set(ScopeMapping.objects.all())
 45        self.application = Application.objects.create(
 46            name=generate_id(),
 47            slug=generate_id(),
 48            provider=self.provider,
 49        )
 50        self.device_flow = create_test_flow()
 51        self.brand = create_test_brand(flow_device_code=self.device_flow)
 52        self.user = create_test_admin_user()
 53        # A single client for the whole user-facing walk: the flow plan lives in the session,
 54        # so splitting the walk across clients would lose it.
 55        self.user_client = APIClient()
 56        self.user_client.force_login(self.user)
 57
 58    def request_device_code(self, scope: str = f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL}") -> dict:
 59        """Run the back channel and return the device authorization response"""
 60        res = self.client.post(
 61            reverse("authentik_providers_oauth2:device"),
 62            data={
 63                "client_id": self.provider.client_id,
 64                "scope": scope,
 65            },
 66        )
 67        self.assertEqual(res.status_code, 200)
 68        return loads(res.content.decode())
 69
 70    def exchange(self, device_code: str):
 71        """Poll the token endpoint for the given device code"""
 72        return self.client.post(
 73            reverse("authentik_providers_oauth2:token"),
 74            data={
 75                "client_id": self.provider.client_id,
 76                "client_secret": self.provider.client_secret,
 77                "grant_type": GRANT_TYPE_DEVICE_CODE,
 78                "device_code": device_code,
 79            },
 80        )
 81
 82    def authorize_via_query_param(self, device: dict):
 83        """Follow verification_uri_complete and run the resulting flow up to the finish stage"""
 84        res = self.user_client.get(device["verification_uri_complete"])
 85        self.assertEqual(res.status_code, 302)
 86        self.assertIn(self.provider.authorization_flow.slug, res.url)
 87        res = self.user_client.get(
 88            reverse(
 89                "authentik_api:flow-executor",
 90                kwargs={"flow_slug": self.provider.authorization_flow.slug},
 91            ),
 92        )
 93        self.assertEqual(res.status_code, 200)
 94        self.assertEqual(
 95            loads(res.content.decode())["component"],
 96            "ak-provider-oauth2-device-code-finish",
 97        )
 98        return res
 99
100    def test_device_flow_end_to_end(self):
101        """Full flow: back channel, authorize via query param, exchange the code"""
102        device = self.request_device_code()
103        token = DeviceToken.objects.filter(device_code=device["device_code"]).first()
104        self.assertIsNotNone(token)
105        self.assertIsNone(token.user)
106
107        # Nothing has authorized the code yet
108        res = self.exchange(device["device_code"])
109        self.assertEqual(res.status_code, 400)
110        self.assertEqual(loads(res.content.decode())["error"], "authorization_pending")
111
112        self.authorize_via_query_param(device)
113
114        token.refresh_from_db()
115        self.assertEqual(token.user, self.user)
116
117        # Acknowledge the finish challenge, which completes the flow
118        res = self.user_client.post(
119            reverse(
120                "authentik_api:flow-executor",
121                kwargs={"flow_slug": self.provider.authorization_flow.slug},
122            ),
123            data={"component": "ak-provider-oauth2-device-code-finish"},
124        )
125        self.assertEqual(res.status_code, 200)
126        self.assertEqual(loads(res.content.decode())["component"], "xak-flow-redirect")
127
128        # The device can now exchange its code
129        res = self.exchange(device["device_code"])
130        self.assertEqual(res.status_code, 200)
131        body = loads(res.content.decode())
132        access_token = AccessToken.objects.filter(token=body["access_token"]).first()
133        self.assertIsNotNone(access_token)
134        self.assertEqual(access_token.user, self.user)
135        self.assertSetEqual(set(access_token.scope), {SCOPE_OPENID, SCOPE_OPENID_EMAIL})
136        # Device code is single-use
137        self.assertFalse(
138            DeviceToken.objects.including_expired()
139            .filter(device_code=device["device_code"])
140            .exists()
141        )
142
143    def test_device_flow_end_to_end_code_entry(self):
144        """Full flow, but the user types the code into the brand's device flow"""
145        device = self.request_device_code()
146
147        res = self.user_client.get(reverse("authentik_providers_oauth2_root:device-login"))
148        self.assertEqual(res.status_code, 302)
149        self.assertIn(self.device_flow.slug, res.url)
150
151        executor = reverse(
152            "authentik_api:flow-executor",
153            kwargs={"flow_slug": self.device_flow.slug},
154        )
155        res = self.user_client.get(executor)
156        self.assertEqual(res.status_code, 200)
157        self.assertEqual(loads(res.content.decode())["component"], "ak-provider-oauth2-device-code")
158
159        res = self.user_client.post(
160            executor,
161            data={
162                "component": "ak-provider-oauth2-device-code",
163                "code": device["user_code"],
164            },
165        )
166        self.assertEqual(res.status_code, 200)
167        body = loads(res.content.decode())
168        self.assertEqual(body["component"], "xak-flow-redirect")
169        self.assertIn(self.provider.authorization_flow.slug, body["to"])
170
171        res = self.user_client.get(
172            reverse(
173                "authentik_api:flow-executor",
174                kwargs={"flow_slug": self.provider.authorization_flow.slug},
175            ),
176        )
177        self.assertEqual(res.status_code, 200)
178        self.assertEqual(
179            loads(res.content.decode())["component"],
180            "ak-provider-oauth2-device-code-finish",
181        )
182
183        token = DeviceToken.objects.filter(device_code=device["device_code"]).first()
184        self.assertEqual(token.user, self.user)
185        self.assertTrue(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists())
186
187    def test_authorize_application_event_context(self):
188        """The finish stage logs an application authorization, same shape as authorize.py"""
189        device = self.request_device_code()
190        self.assertFalse(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists())
191
192        self.authorize_via_query_param(device)
193
194        event = Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).first()
195        self.assertIsNotNone(event)
196        self.assertEqual(event.context["authorized_application"]["name"], self.application.name)
197        self.assertEqual(event.context["authorized_application"]["pk"], self.application.pk.hex)
198        self.assertEqual(event.context["flow"], self.provider.authorization_flow.pk.hex)
199        self.assertSetEqual(
200            set(event.context["scopes"].split()), {SCOPE_OPENID, SCOPE_OPENID_EMAIL}
201        )
202        self.assertEqual(event.user["username"], self.user.username)
203
204    def test_finish_stage_binds_session(self):
205        """The finish stage binds the user's session, which the access token inherits"""
206        device = self.request_device_code()
207        self.authorize_via_query_param(device)
208
209        token = DeviceToken.objects.filter(device_code=device["device_code"]).first()
210        self.assertIsNotNone(token.session)
211        self.assertEqual(token.session.user, self.user)
212
213        res = self.exchange(device["device_code"])
214        self.assertEqual(res.status_code, 200)
215        access_token = AccessToken.objects.filter(
216            token=loads(res.content.decode())["access_token"]
217        ).first()
218        self.assertIsNotNone(access_token.session)
219        self.assertEqual(access_token.session.session_id, token.session.session_id)
220
221    def test_finish_stage_auth_time_from_login_event(self):
222        """With a session bound, auth_time comes from the login event instead of now()"""
223        device = self.request_device_code()
224        self.authorize_via_query_param(device)
225
226        token = DeviceToken.objects.filter(device_code=device["device_code"]).first()
227        login_event = get_login_event(token.session)
228        self.assertIsNotNone(login_event)
229
230        res = self.exchange(device["device_code"])
231        self.assertEqual(res.status_code, 200)
232        access_token = AccessToken.objects.filter(
233            token=loads(res.content.decode())["access_token"]
234        ).first()
235        self.assertEqual(access_token.auth_time, login_event.created)

Walk the whole device code flow: back channel, user code entry, finish stage, token exchange. Nothing else in the suite executes OAuthDeviceCodeFinishStage.

@apply_blueprint('system/providers-oauth2.yaml')
def setUp(self) -> None:
34    @apply_blueprint("system/providers-oauth2.yaml")
35    def setUp(self) -> None:
36        super().setUp()
37        self.provider = OAuth2Provider.objects.create(
38            name=generate_id(),
39            client_id=generate_id(),
40            authorization_flow=create_test_flow(),
41            signing_key=self.keypair,
42            grant_types=[GrantType.DEVICE_CODE],
43        )
44        self.provider.property_mappings.set(ScopeMapping.objects.all())
45        self.application = Application.objects.create(
46            name=generate_id(),
47            slug=generate_id(),
48            provider=self.provider,
49        )
50        self.device_flow = create_test_flow()
51        self.brand = create_test_brand(flow_device_code=self.device_flow)
52        self.user = create_test_admin_user()
53        # A single client for the whole user-facing walk: the flow plan lives in the session,
54        # so splitting the walk across clients would lose it.
55        self.user_client = APIClient()
56        self.user_client.force_login(self.user)

Hook method for setting up the test fixture before exercising it.

def request_device_code(self, scope: str = 'openid email') -> dict:
58    def request_device_code(self, scope: str = f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL}") -> dict:
59        """Run the back channel and return the device authorization response"""
60        res = self.client.post(
61            reverse("authentik_providers_oauth2:device"),
62            data={
63                "client_id": self.provider.client_id,
64                "scope": scope,
65            },
66        )
67        self.assertEqual(res.status_code, 200)
68        return loads(res.content.decode())

Run the back channel and return the device authorization response

def exchange(self, device_code: str):
70    def exchange(self, device_code: str):
71        """Poll the token endpoint for the given device code"""
72        return self.client.post(
73            reverse("authentik_providers_oauth2:token"),
74            data={
75                "client_id": self.provider.client_id,
76                "client_secret": self.provider.client_secret,
77                "grant_type": GRANT_TYPE_DEVICE_CODE,
78                "device_code": device_code,
79            },
80        )

Poll the token endpoint for the given device code

def authorize_via_query_param(self, device: dict):
82    def authorize_via_query_param(self, device: dict):
83        """Follow verification_uri_complete and run the resulting flow up to the finish stage"""
84        res = self.user_client.get(device["verification_uri_complete"])
85        self.assertEqual(res.status_code, 302)
86        self.assertIn(self.provider.authorization_flow.slug, res.url)
87        res = self.user_client.get(
88            reverse(
89                "authentik_api:flow-executor",
90                kwargs={"flow_slug": self.provider.authorization_flow.slug},
91            ),
92        )
93        self.assertEqual(res.status_code, 200)
94        self.assertEqual(
95            loads(res.content.decode())["component"],
96            "ak-provider-oauth2-device-code-finish",
97        )
98        return res

Follow verification_uri_complete and run the resulting flow up to the finish stage

def test_device_flow_end_to_end(self):
100    def test_device_flow_end_to_end(self):
101        """Full flow: back channel, authorize via query param, exchange the code"""
102        device = self.request_device_code()
103        token = DeviceToken.objects.filter(device_code=device["device_code"]).first()
104        self.assertIsNotNone(token)
105        self.assertIsNone(token.user)
106
107        # Nothing has authorized the code yet
108        res = self.exchange(device["device_code"])
109        self.assertEqual(res.status_code, 400)
110        self.assertEqual(loads(res.content.decode())["error"], "authorization_pending")
111
112        self.authorize_via_query_param(device)
113
114        token.refresh_from_db()
115        self.assertEqual(token.user, self.user)
116
117        # Acknowledge the finish challenge, which completes the flow
118        res = self.user_client.post(
119            reverse(
120                "authentik_api:flow-executor",
121                kwargs={"flow_slug": self.provider.authorization_flow.slug},
122            ),
123            data={"component": "ak-provider-oauth2-device-code-finish"},
124        )
125        self.assertEqual(res.status_code, 200)
126        self.assertEqual(loads(res.content.decode())["component"], "xak-flow-redirect")
127
128        # The device can now exchange its code
129        res = self.exchange(device["device_code"])
130        self.assertEqual(res.status_code, 200)
131        body = loads(res.content.decode())
132        access_token = AccessToken.objects.filter(token=body["access_token"]).first()
133        self.assertIsNotNone(access_token)
134        self.assertEqual(access_token.user, self.user)
135        self.assertSetEqual(set(access_token.scope), {SCOPE_OPENID, SCOPE_OPENID_EMAIL})
136        # Device code is single-use
137        self.assertFalse(
138            DeviceToken.objects.including_expired()
139            .filter(device_code=device["device_code"])
140            .exists()
141        )

Full flow: back channel, authorize via query param, exchange the code

def test_device_flow_end_to_end_code_entry(self):
143    def test_device_flow_end_to_end_code_entry(self):
144        """Full flow, but the user types the code into the brand's device flow"""
145        device = self.request_device_code()
146
147        res = self.user_client.get(reverse("authentik_providers_oauth2_root:device-login"))
148        self.assertEqual(res.status_code, 302)
149        self.assertIn(self.device_flow.slug, res.url)
150
151        executor = reverse(
152            "authentik_api:flow-executor",
153            kwargs={"flow_slug": self.device_flow.slug},
154        )
155        res = self.user_client.get(executor)
156        self.assertEqual(res.status_code, 200)
157        self.assertEqual(loads(res.content.decode())["component"], "ak-provider-oauth2-device-code")
158
159        res = self.user_client.post(
160            executor,
161            data={
162                "component": "ak-provider-oauth2-device-code",
163                "code": device["user_code"],
164            },
165        )
166        self.assertEqual(res.status_code, 200)
167        body = loads(res.content.decode())
168        self.assertEqual(body["component"], "xak-flow-redirect")
169        self.assertIn(self.provider.authorization_flow.slug, body["to"])
170
171        res = self.user_client.get(
172            reverse(
173                "authentik_api:flow-executor",
174                kwargs={"flow_slug": self.provider.authorization_flow.slug},
175            ),
176        )
177        self.assertEqual(res.status_code, 200)
178        self.assertEqual(
179            loads(res.content.decode())["component"],
180            "ak-provider-oauth2-device-code-finish",
181        )
182
183        token = DeviceToken.objects.filter(device_code=device["device_code"]).first()
184        self.assertEqual(token.user, self.user)
185        self.assertTrue(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists())

Full flow, but the user types the code into the brand's device flow

def test_authorize_application_event_context(self):
187    def test_authorize_application_event_context(self):
188        """The finish stage logs an application authorization, same shape as authorize.py"""
189        device = self.request_device_code()
190        self.assertFalse(Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).exists())
191
192        self.authorize_via_query_param(device)
193
194        event = Event.objects.filter(action=EventAction.AUTHORIZE_APPLICATION).first()
195        self.assertIsNotNone(event)
196        self.assertEqual(event.context["authorized_application"]["name"], self.application.name)
197        self.assertEqual(event.context["authorized_application"]["pk"], self.application.pk.hex)
198        self.assertEqual(event.context["flow"], self.provider.authorization_flow.pk.hex)
199        self.assertSetEqual(
200            set(event.context["scopes"].split()), {SCOPE_OPENID, SCOPE_OPENID_EMAIL}
201        )
202        self.assertEqual(event.user["username"], self.user.username)

The finish stage logs an application authorization, same shape as authorize.py

def test_finish_stage_binds_session(self):
204    def test_finish_stage_binds_session(self):
205        """The finish stage binds the user's session, which the access token inherits"""
206        device = self.request_device_code()
207        self.authorize_via_query_param(device)
208
209        token = DeviceToken.objects.filter(device_code=device["device_code"]).first()
210        self.assertIsNotNone(token.session)
211        self.assertEqual(token.session.user, self.user)
212
213        res = self.exchange(device["device_code"])
214        self.assertEqual(res.status_code, 200)
215        access_token = AccessToken.objects.filter(
216            token=loads(res.content.decode())["access_token"]
217        ).first()
218        self.assertIsNotNone(access_token.session)
219        self.assertEqual(access_token.session.session_id, token.session.session_id)

The finish stage binds the user's session, which the access token inherits

def test_finish_stage_auth_time_from_login_event(self):
221    def test_finish_stage_auth_time_from_login_event(self):
222        """With a session bound, auth_time comes from the login event instead of now()"""
223        device = self.request_device_code()
224        self.authorize_via_query_param(device)
225
226        token = DeviceToken.objects.filter(device_code=device["device_code"]).first()
227        login_event = get_login_event(token.session)
228        self.assertIsNotNone(login_event)
229
230        res = self.exchange(device["device_code"])
231        self.assertEqual(res.status_code, 200)
232        access_token = AccessToken.objects.filter(
233            token=loads(res.content.decode())["access_token"]
234        ).first()
235        self.assertEqual(access_token.auth_time, login_event.created)

With a session bound, auth_time comes from the login event instead of now()