← All articles
Best PracticesNov 29, 202619 min read

Block Device Code Flow with Conditional Access: A Step-by-Step Guide

Serdal Tarkan AltunSecurity Research EngineerLinkedIn

Summary

Device code flow lets a user sign in to a device without a browser by entering a short code on Microsoft's sign-in page from another device. To block device code flow, create a Conditional Access policy with the authentication flows condition, test it in report-only mode, exclude only the accounts that need the flow, then turn it on.

Quick steps

  1. Run the read-only script to list the Conditional Access policies that already use the authentication flows condition, including Microsoft's managed Block device code flow policy.
  2. Query the sign-in logs for device code sign-ins and give every legitimate use an owner.
  3. Put Teams device resource accounts and other approved users in exception groups.
  4. Create a policy that blocks device code flow for all users and all resources, excluding your emergency access and exception groups, in report-only mode.
  5. Review what the policy would have blocked, then turn it on and align the Microsoft-managed policy.
  6. Block authentication transfer as well, unless you need it.
  7. Alert on device code sign-ins outside the exceptions and on every change to the policy.

Applies to: Microsoft Entra ID with Microsoft Entra ID P1 or P2, as of November 2026; the authentication transfer condition is in preview. The scripts use Microsoft Graph PowerShell v1.0 cmdlets and run in Windows PowerShell 5.1 or PowerShell 7. The KQL queries need the sign-in and audit logs in a Log Analytics workspace.

What is device code flow, and why block it?

Device code flow is Microsoft Entra ID's implementation of the OAuth 2.0 device authorization grant, a standard for internet-connected devices that lack a browser or can't take typed input easily. RFC 8628 names smart TVs, media consoles, picture frames and printers as examples. The device shows a URL and a code, and the user approves the request on a second device such as a phone or a PC. Attackers abuse the same flow for phishing, so Microsoft recommends blocking it wherever possible.

In Microsoft Entra ID, the client requests a device code and a user code from the /devicecode endpoint. The user enters the code at the verification URL and signs in, while the client polls the token endpoint until it receives an access token and a refresh token. According to Microsoft's device authorization grant article, the user has 15 minutes from the request to sign in, the default value of expires_in.

How does device code phishing work?

Device code phishing turns the flow around: the attacker starts the request on a machine they control, sends the code to a user with a pretext and receives the tokens when the user signs in. RFC 8628 describes this risk as remote phishing in Section 5.4. The sign-in page is genuine and the user completes any MFA prompt themselves; Microsoft notes that because the page is real, the attack can be harder for users to recognize. MITRE ATT&CK describes device code phishing under T1566.002, Phishing: Spearphishing Link, and it's one form of identity-based attack.

Microsoft Threat Intelligence has reported it in several campaigns:

  • Storm-2372 conducts device code phishing campaign, February 13, 2025: a campaign active since August 2024 against governments, NGOs and many industries. A February 14, 2025 update says the actor moved to the Microsoft Authentication Broker client ID, which let it register a device and obtain a Primary Refresh Token. A July 31, 2026 update assesses Storm-2372 as an initial access sub-cluster of Midnight Blizzard.
  • Unmasking EvilTokens: Getting to the root of device code phishing, September 22, 2026: a phishing-as-a-service platform that emerged in February 2026. Microsoft says its campaigns compromised more than 12,000 inboxes in over 10,000 organizations, and that attackers use the flow to circumvent traditional MFA protections.

Both reports open their mitigation advice the same way: allow device code flow only where necessary and block it wherever possible with Conditional Access. Our device code phishing detection rules cover the detection side; this guide covers prevention.

What is authentication transfer?

Authentication transfer is the second flow the same condition controls. A user signed in to a Microsoft app on a PC scans a QR code with a phone and is signed in to the same app there without reentering credentials. Microsoft's authentication transfer article marks the feature as preview and says it's enabled by default for all users.

Device claims such as compliance don't transfer, so the phone must meet device-based policies on its own. The same article says the flow bypasses non-Microsoft mobile device management solutions, and recommends blocking it unless you have a documented business need for cross-device sign-in.

Which Conditional Access settings control these flows?

The authentication flows condition in Conditional Access targets device code flow and authentication transfer. Combined with the Block access grant control, it stops the flow for the users and resources in scope.

Setting Where (portal / Microsoft Graph) Recommended value Effect
Authentication flows Conditions > Authentication Flows > Configure: Yes / conditions.authenticationFlows.transferMethods Device code flow / deviceCodeFlow The policy applies to device code sign-ins and to sessions that started with one
Authentication transfer Same condition, in a second policy / authenticationTransfer Blocked unless you need it Stops the QR code transfer from a PC to a phone
Users Users or workload identities / conditions.users Include All users; exclude the emergency access and exception groups Every exception stays explicit and auditable
Target resources Target resources > Resources (formerly cloud apps) / conditions.applications Include All resources; exclude Device Registration Service if devices register with device code flow Covers every app without breaking device registration
Grant Access controls > Grant / grantControls.builtInControls Block access / block Refuses the sign-in
Policy state Enable policy / state Report-only (enabledForReportingButNotEnforced) first, then On (enabled) Measures the impact before enforcing

The conditionalAccessAuthenticationFlows resource lists none, deviceCodeFlow, authenticationTransfer and unknownFutureValue as the values of transferMethods. Microsoft's authentication flows article adds protocol tracking: a session that started with device code flow or authentication transfer stays marked through later token refreshes. A block policy can therefore stop a later sign-in in that session even when it uses another flow, and the sign-in log shows this in the Original transfer method property.

Before you start

Plan the exceptions before you create the policy. Test the whole sequence in a lab tenant first, because a block policy for all users and all resources can sign shared devices out.

Which roles and licenses do you need?

Task Least privileged role in Microsoft's articles
Create, change or restore Conditional Access policies Conditional Access Administrator (Security Administrator can also create and change them)
Run the read-only audit script Global Reader or Conditional Access Administrator
Read sign-in logs in the admin center Reports Reader; the Conditional Access details need Global Reader, Security Reader, Security Administrator or Conditional Access Administrator
Open the Policy impact view Security Reader
Send sign-in and audit logs to Log Analytics Security Administrator

As of November 2026, Microsoft's licensing reference says Conditional Access needs Microsoft Entra ID P1 and that Microsoft 365 Business Premium licenses also include it. Microsoft's deployment plan lists "Restrict device code flow" and "Authentication transfer is blocked" as P1 scenarios for all users.

Prepare the groups and the logs

  • An emergency access group for your break glass accounts, excluded from every Conditional Access policy. Our guide to emergency access accounts shows how to build and protect it.
  • A security group for Teams device resource accounts, if you run Teams Rooms or other Teams devices.
  • A security group for any other approved device code users that remain after Step 2.
  • The user sign-in logs, non-interactive user sign-in logs and audit logs routed to a Log Analytics workspace under Entra ID > Monitoring & health > Diagnostic settings.
  • A note to the help desk and to the owners of meeting rooms and shared devices, with the date the block goes on.

Step 1: Audit your Conditional Access policies

Start by finding out what already controls authentication flows in your tenant, including Microsoft's managed policy. The script below reads every Conditional Access policy, keeps the ones whose authentication flows condition targets device code flow or authentication transfer, and flags gaps. It's read-only and reads policy settings only.

Run it on an admin workstation as Global Reader, after connecting with Policy.Read.All, the least privileged permission for listing policies:

Connect-MgGraph -Scopes 'Policy.Read.All'
#Requires -Version 5.1
#Requires -Modules Microsoft.Graph.Authentication, Microsoft.Graph.Identity.SignIns

<#
.SYNOPSIS
    Read-only report of the Conditional Access policies that use the authentication flows condition.

.DESCRIPTION
    Reads every Conditional Access policy and returns one row for each policy whose authentication
    flows condition targets device code flow or authentication transfer. Each row shows the policy
    state, whether Microsoft manages the policy, whether it blocks access, whom and what it targets,
    which groups and users it excludes and whether it excludes the Device Registration Service.
    The Findings column lists what to review:

      Report-only          the policy records what it would do but blocks nothing
      Off                  the policy is disabled
      Doesn't block        the grant control isn't Block access
      Not all users        the policy doesn't include All users
      Not all resources    the policy doesn't include All resources
      No group exclusions  no group is excluded, so check your emergency access accounts
      DRS not excluded     a device code flow policy for all resources doesn't exclude the
                           Device Registration Service

    When no enabled policy blocks device code flow, a summary row says so. Writes one CSV file and
    returns the rows. It reads policy settings only and changes nothing.

.PARAMETER OutputPath
    Path of the CSV report, for example 'C:\Reports\DeviceCode\auth-flow-policies.csv'.

.EXAMPLE
    .\Get-EntraAuthFlowPolicyAudit.ps1 -OutputPath 'C:\Reports\DeviceCode\auth-flow-policies.csv'

.NOTES
    Read-only. Makes no change in Microsoft Entra ID. Writes only the CSV report.
    Run it in a session opened with delegated permissions:
        Connect-MgGraph -Scopes 'Policy.Read.All'
    as a Global Reader or Conditional Access Administrator.
#>
[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [string]$OutputPath
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

if ($null -eq (Get-MgContext)) {
    throw 'No Microsoft Graph session. Run Connect-MgGraph first.'
}

$reportFolder = Split-Path -Path $OutputPath -Parent
if ($reportFolder -and -not (Test-Path -Path $reportFolder -PathType Container)) {
    throw "Report folder not found: $reportFolder"
}

# Client ID of the Device Registration Service, from Microsoft's authentication flows article
$deviceRegistrationService = '01cb2876-7ebd-4aa4-9cc9-d28bd4d359a9'

$rows = New-Object System.Collections.Generic.List[object]
foreach ($policy in @(Get-MgIdentityConditionalAccessPolicy -All)) {
    $conditions = $policy.Conditions
    if ($null -eq $conditions -or $null -eq $conditions.AuthenticationFlows) { continue }
    $methods = [string]$conditions.AuthenticationFlows.TransferMethods
    if ($methods -notmatch 'deviceCodeFlow|authenticationTransfer') { continue }

    # 1. Users, groups and roles the policy includes and excludes
    $includeUsers = @(); $targets = @(); $excludeUsers = @(); $excludeGroups = @(); $excludeRoles = @()
    if ($null -ne $conditions.Users) {
        $includeUsers = @($conditions.Users.IncludeUsers | Where-Object { $_ })
        $targets = $includeUsers + @($conditions.Users.IncludeGroups | Where-Object { $_ }) + @($conditions.Users.IncludeRoles | Where-Object { $_ })
        $excludeUsers = @($conditions.Users.ExcludeUsers | Where-Object { $_ })
        $excludeGroups = @($conditions.Users.ExcludeGroups | Where-Object { $_ })
        $excludeRoles = @($conditions.Users.ExcludeRoles | Where-Object { $_ })
    }

    # 2. Resources the policy includes and excludes
    $includeApps = @(); $excludeApps = @()
    if ($null -ne $conditions.Applications) {
        $includeApps = @($conditions.Applications.IncludeApplications | Where-Object { $_ })
        $excludeApps = @($conditions.Applications.ExcludeApplications | Where-Object { $_ })
    }

    # 3. Grant controls
    $grant = @()
    if ($null -ne $policy.GrantControls) {
        $grant = @($policy.GrantControls.BuiltInControls | Where-Object { $_ })
    }
    $blocks = $grant -contains 'block'
    $drsExcluded = $excludeApps -contains $deviceRegistrationService

    $findings = New-Object System.Collections.Generic.List[string]
    if ($policy.State -eq 'enabledForReportingButNotEnforced') { $findings.Add('Report-only') }
    if ($policy.State -eq 'disabled') { $findings.Add('Off') }
    if (-not $blocks) { $findings.Add("Doesn't block") }
    if ($includeUsers -notcontains 'All') { $findings.Add('Not all users') }
    if ($includeApps -notcontains 'All') { $findings.Add('Not all resources') }
    if ($excludeGroups.Count -eq 0) { $findings.Add('No group exclusions') }
    if ($methods -match 'deviceCodeFlow' -and $includeApps -contains 'All' -and -not $drsExcluded) { $findings.Add('DRS not excluded') }

    $rows.Add([pscustomobject]@{
        PolicyName         = $policy.DisplayName
        PolicyId           = $policy.Id
        State              = $policy.State
        ManagedByMicrosoft = ($policy.DisplayName -like 'Microsoft-managed:*')
        TransferMethods    = $methods
        BlocksAccess       = $blocks
        Targets            = ($targets -join '; ')
        ExcludedGroups     = ($excludeGroups -join '; ')
        ExcludedUsers      = $excludeUsers.Count
        ExcludedRoles      = $excludeRoles.Count
        Resources          = ($includeApps -join '; ')
        DrsExcluded        = $drsExcluded
        ModifiedUtc        = $policy.ModifiedDateTime
        Findings           = ($findings -join '; ')
    })
}

# 4. Summary row when nothing enforces a device code flow block
$enforced = @($rows | Where-Object { $_.State -eq 'enabled' -and $_.BlocksAccess -and $_.TransferMethods -match 'deviceCodeFlow' })
if ($enforced.Count -eq 0) {
    $rows.Add([pscustomobject]@{
        PolicyName         = '(summary)'
        PolicyId           = ''
        State              = ''
        ManagedByMicrosoft = ''
        TransferMethods    = ''
        BlocksAccess       = ''
        Targets            = ''
        ExcludedGroups     = ''
        ExcludedUsers      = ''
        ExcludedRoles      = ''
        Resources          = ''
        DrsExcluded        = ''
        ModifiedUtc        = ''
        Findings           = 'No enabled policy blocks device code flow'
    })
}

$rows | Export-Csv -Path $OutputPath -NoTypeInformation -Encoding UTF8
$rows
.\Get-EntraAuthFlowPolicyAudit.ps1 -OutputPath 'C:\Reports\DeviceCode\auth-flow-policies.csv'

Example output (the values are illustrative):

PolicyName         : Block device code flow (pilot)
PolicyId           : 33333333-3333-3333-3333-333333333333
State              : enabledForReportingButNotEnforced
ManagedByMicrosoft : False
TransferMethods    : deviceCodeFlow
BlocksAccess       : True
Targets            : 55555555-5555-5555-5555-555555555555
ExcludedGroups     :
ExcludedUsers      : 0
ExcludedRoles      : 0
Resources          : All
DrsExcluded        : False
ModifiedUtc        : 9/14/2026 8:12:44 AM
Findings           : Report-only; Not all users; No group exclusions; DRS not excluded

PolicyName         : (summary)
PolicyId           :
State              :
ManagedByMicrosoft :
TransferMethods    :
BlocksAccess       :
Targets            :
ExcludedGroups     :
ExcludedUsers      :
ExcludedRoles      :
Resources          :
DrsExcluded        :
ModifiedUtc        :
Findings           : No enabled policy blocks device code flow

How to read the results:

  • Report-only or Off: the policy blocks nothing yet. Microsoft turns its own managed policy on later if you leave it in report-only mode.
  • Not all users or Not all resources: Microsoft recommends getting as close as possible to a unilateral block, so a narrow scope needs a documented reason.
  • No group exclusions: no group is excluded, so the emergency access accounts may not be. Fix this before the policy goes on.
  • DRS not excluded: this matters only if devices register through device code flow, which Step 2 tells you.

Is Microsoft's managed Block device code flow policy in your tenant?

As of November 2026, the Microsoft-managed Conditional Access policies include Block device code flow. Microsoft creates managed policies in report-only mode and sends email and Message center notices two weeks before it enables them. It turns them on no less than 30 days after they arrive if you leave them in report-only mode, sooner in some cases that the notices and the policy details mention.

You can exclude identities and change the state, but you can't rename or delete a managed policy. Managed policies show Microsoft in the Created by column of the policy list.

Step 2: Find legitimate device code usage in the sign-in logs

Find out who signs in with device code flow before you block it, because any legitimate use you miss breaks when the policy goes on. Microsoft suggests two ways: a policy in report-only mode, and the sign-in logs filtered on the authentication protocol.

In the Microsoft Entra admin center, browse to Entra ID > Monitoring & health > Sign-in logs and add the Authentication protocol filter with the device code option. For both sign-in tables and a longer window, run the query below in Log Analytics. The SigninLogs table reference lists deviceCode among the values of AuthenticationProtocol, and OriginalTransferMethod records the transfer method that started the session.

// Device code sign-ins in the last 30 days, interactive and non-interactive, by account, app and resource.
// Read-only. Needs the user sign-in logs and non-interactive user sign-in logs in the workspace.
// DirectDeviceCode counts sign-ins that used the flow; the rest are later refreshes of a device code session.
union SigninLogs, AADNonInteractiveUserSignInLogs
| where TimeGenerated > ago(30d)
| where AuthenticationProtocol == "deviceCode" or OriginalTransferMethod contains "deviceCode"
| summarize SignIns = count(), DirectDeviceCode = countif(AuthenticationProtocol == "deviceCode"),
    ResultTypes = make_set(ResultType, 10), IPAddresses = make_set(IPAddress, 10),
    FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated)
    by UserPrincipalName, AppDisplayName, AppId, ResourceDisplayName
| order by DirectDeviceCode desc, SignIns desc

For each row, Microsoft's Teams device guidance asks you to identify the user, the app or resource, the location, the device context and a business owner. Then sort every use into one of these cases:

Usage you find What Microsoft says What to do in the policy
Teams Rooms, Teams Android and shared Teams devices Some Teams devices use device code flow at first registration, at reprovisioning and in some reauthentication scenarios Exclude a persistent group of Teams device resource accounts and exclude the Device Registration Service
Personal Teams devices Harder to scope, because the user's account could then use device code flow elsewhere; avoid broad user exclusions Document the risk, monitor it and review any user exception regularly
Device registration through device code flow Since early September 2024, authentication flows policies that target all resources also apply to the Device Registration Service Exclude the Device Registration Service, client ID 01cb2876-7ebd-4aa4-9cc9-d28bd4d359a9
Administrators signing in to command-line tools with a code Prefer browser-based or brokered sign-in for users No exception; sign in without the device code option
Scripts that sign in as a user Prefer managed identities or workload identity federation for automation No exception; move the script to a workload identity
Legacy tooling that can't be updated Allow it only in well-documented, secured use cases An approved group, treated as a documented risk acceptance with an owner and a review cadence

Expect some command-line tools in the results. Microsoft's az login reference says Azure CLI uses Web Account Manager on Windows and a browser on Linux and macOS by default. With browser sign-in, it falls back to device code flow when it can't open a browser, and --use-device-code forces the flow. Microsoft Graph PowerShell has the same option, Connect-MgGraph -UseDeviceCode.

Step 3: Create the exception groups

Create the exception groups before the policy, so the policy can exclude them from the start. Microsoft's Teams guidance uses two persistent groups: one for Teams device resource accounts, and one for approved non-Teams scenarios.

  • Create both as security groups with assigned membership, each with a named owner.
  • Add only resource accounts to the Teams group, never the technicians or administrators who set up the devices.
  • Record the owner, the device and a change or ticket ID for each member, and remove the account when the device is retired.

Keep the groups small. An exclusion applies to the account, not to one app, so an excluded account can use device code flow for any resource the policy covers. We recommend treating every membership change as a change to the policy and alerting on it, because whoever can add a member can reopen the flow for that account.

Teams resource accounts that use passwordless authentication need device code flow only at initial provisioning. Microsoft still says to keep them in the persistent group, so reprovisioning and recovery keep working.

Step 4: Create a policy to block device code flow in report-only mode

Create the policy in report-only mode, so it records what it would block without blocking anything. Use the portal or the script; both produce the same policy.

In the Microsoft Entra admin center

  1. Sign in as at least a Conditional Access Administrator, browse to Entra ID > Conditional Access > Policies, select New policy and give it a name.
  2. Under Users or workload identities, include All users. Under Exclude > Users and groups, select the emergency access group and the exception groups.
  3. Under Target resources > Resources (formerly cloud apps), include All resources (formerly 'All cloud apps'). If devices register with device code flow, under Exclude choose Select resources > Select specific resources and add Device Registration Service.
  4. Under Conditions > Authentication Flows, set Configure to Yes, select Device code flow and select Done.
  5. Under Access controls > Grant, select Block access, then Select.
  6. Set Enable policy to Report-only and select Create.

With Microsoft Graph PowerShell

The script below creates the same policy and supports -WhatIf and -Confirm. It always uses report-only mode, checks that each excluded group exists and is a security group, and refuses to create a second policy with the same name. Microsoft's steps for blocking authentication flows use the same settings.

Creating a policy needs Policy.Read.All and Policy.ReadWrite.ConditionalAccess with a Conditional Access Administrator or Security Administrator; the group check adds Group.Read.All. Microsoft notes a known permissions issue with this API that may require consent to several permissions.

Connect-MgGraph -Scopes 'Policy.Read.All', 'Policy.ReadWrite.ConditionalAccess', 'Group.Read.All'
#Requires -Version 5.1
#Requires -Modules Microsoft.Graph.Authentication, Microsoft.Graph.Groups, Microsoft.Graph.Identity.SignIns

<#
.SYNOPSIS
    Creates a report-only Conditional Access policy that blocks device code flow or authentication transfer.

.DESCRIPTION
    Builds one Conditional Access policy that targets all users and all resources, uses the
    authentication flows condition with the transfer method you select and grants Block access.
    The policy excludes the emergency access group and every exception group you pass and, with
    ExcludeDeviceRegistrationService, the Device Registration Service resource.

    The policy is always created in report-only mode (enabledForReportingButNotEnforced), so it
    blocks nothing until you turn it on. Before it creates anything, the script checks that every
    excluded group exists and is a security group, and it stops if a policy with the same display
    name already exists. Run it with -WhatIf first; it asks for confirmation unless you pass
    -Confirm:$false.

.PARAMETER DisplayName
    Name of the new policy, for example 'Block device code flow'.

.PARAMETER EmergencyAccessGroupId
    Object ID of the group that holds your emergency access accounts.

.PARAMETER ExceptionGroupId
    Optional. Object IDs of the approved exception groups, for example the group of Teams device
    resource accounts.

.PARAMETER TransferMethod
    deviceCodeFlow (default) or authenticationTransfer. Create one policy per flow.

.PARAMETER ExcludeDeviceRegistrationService
    Exclude the Device Registration Service resource, for devices that register through device
    code flow.

.EXAMPLE
    .\New-EntraAuthFlowBlockPolicy.ps1 -DisplayName 'Block device code flow' -EmergencyAccessGroupId '11111111-1111-1111-1111-111111111111' -ExceptionGroupId '22222222-2222-2222-2222-222222222222' -ExcludeDeviceRegistrationService -WhatIf

.NOTES
    Changes configuration. Creates one Conditional Access policy in Microsoft Entra ID, in
    report-only mode.
    Run it in a session opened with delegated permissions:
        Connect-MgGraph -Scopes 'Policy.Read.All','Policy.ReadWrite.ConditionalAccess','Group.Read.All'
    as a Conditional Access Administrator or Security Administrator.
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param(
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [string]$DisplayName,

    [Parameter(Mandatory = $true)]
    [ValidatePattern('^[0-9a-fA-F-]{36}$')]
    [string]$EmergencyAccessGroupId,

    [ValidatePattern('^[0-9a-fA-F-]{36}$')]
    [string[]]$ExceptionGroupId = @(),

    [ValidateSet('deviceCodeFlow', 'authenticationTransfer')]
    [string]$TransferMethod = 'deviceCodeFlow',

    [switch]$ExcludeDeviceRegistrationService
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

if ($null -eq (Get-MgContext)) {
    throw 'No Microsoft Graph session. Run Connect-MgGraph first.'
}

# 1. Every excluded group must exist and be a security group
$excludeGroups = @(@($EmergencyAccessGroupId) + $ExceptionGroupId | Sort-Object -Unique)
foreach ($groupId in $excludeGroups) {
    $group = Get-MgGroup -GroupId $groupId -Property 'id', 'displayName', 'securityEnabled'
    if ($group.SecurityEnabled -ne $true) { throw "$($group.DisplayName) isn't a security group." }
}

# 2. Stop if a policy with the same name exists
$existing = @(Get-MgIdentityConditionalAccessPolicy -All | Where-Object { $_.DisplayName -eq $DisplayName })
if ($existing.Count -gt 0) {
    throw "A policy named '$DisplayName' already exists: $($existing[0].Id)"
}

# 3. Policy body: all users and all resources, the selected flow, Block access, report-only
$applications = @{ includeApplications = @('All') }
if ($ExcludeDeviceRegistrationService) {
    # Client ID of the Device Registration Service, from Microsoft's authentication flows article
    $applications.excludeApplications = @('01cb2876-7ebd-4aa4-9cc9-d28bd4d359a9')
}
$body = @{
    displayName   = $DisplayName
    state         = 'enabledForReportingButNotEnforced'
    conditions    = @{
        users               = @{ includeUsers = @('All'); excludeGroups = $excludeGroups }
        applications        = $applications
        clientAppTypes      = @('all')
        authenticationFlows = @{ transferMethods = $TransferMethod }
    }
    grantControls = @{ operator = 'OR'; builtInControls = @('block') }
}

# 4. Create the policy
if ($PSCmdlet.ShouldProcess($DisplayName, "Create a report-only Conditional Access policy that blocks $TransferMethod")) {
    $policy = New-MgIdentityConditionalAccessPolicy -BodyParameter $body -Confirm:$false
    [pscustomobject]@{
        PolicyName      = $policy.DisplayName
        PolicyId        = $policy.Id
        State           = $policy.State
        TransferMethods = $TransferMethod
        ExcludedGroups  = ($excludeGroups -join '; ')
        DrsExcluded     = [bool]$ExcludeDeviceRegistrationService
    }
}

Preview the policy first:

.\New-EntraAuthFlowBlockPolicy.ps1 -DisplayName 'Block device code flow' -EmergencyAccessGroupId '11111111-1111-1111-1111-111111111111' -ExceptionGroupId '22222222-2222-2222-2222-222222222222', '44444444-4444-4444-4444-444444444444' -ExcludeDeviceRegistrationService -WhatIf
What if: Performing the operation "Create a report-only Conditional Access policy that blocks deviceCodeFlow" on target "Block device code flow".

Run it again without -WhatIf and note the policy ID it returns. The new policy writes an Add Conditional Access policy record to the audit log.

Step 5: Review the report-only results

Leave the policy in report-only mode long enough to catch accounts that sign in rarely; Microsoft's deployment plan suggests at least one week per policy. Report-only mode evaluates the policy at sign-in and logs the result without enforcing it.

Three places show the result:

  • The Policy impact tab of the policy, in preview, shows interactive sign-ins over the past 24 hours, 7 days or 1 month.
  • The Report-only tab of a sign-in log entry reads Report-only: Failure when the policy would have blocked that sign-in.
  • Log Analytics, with the query below, lists every account the policy would have blocked.

The query reads ConditionalAccessPolicies, the list of policies evaluated for each sign-in. For a report-only policy that would block, Microsoft's Graph reference for applied policies gives the result value reportOnlyFailure. The column is dynamic in SigninLogs and a string in AADNonInteractiveUserSignInLogs, so the query parses both before the union.

// Sign-ins that the device code block policy would have blocked while it runs in report-only mode.
// Read-only. Replace PolicyId with the object ID of your policy.
let PolicyId = "33333333-3333-3333-3333-333333333333";
let Interactive = SigninLogs
    | where TimeGenerated > ago(14d)
    | project TimeGenerated, UserPrincipalName, AppDisplayName, ResourceDisplayName, AuthenticationProtocol,
        OriginalTransferMethod, Policies = parse_json(tostring(ConditionalAccessPolicies));
let NonInteractive = AADNonInteractiveUserSignInLogs
    | where TimeGenerated > ago(14d)
    | project TimeGenerated, UserPrincipalName, AppDisplayName, ResourceDisplayName, AuthenticationProtocol,
        OriginalTransferMethod, Policies = parse_json(ConditionalAccessPolicies);
union Interactive, NonInteractive
| mv-expand Policy = Policies
| where tostring(Policy.id) == PolicyId and tostring(Policy.result) == "reportOnlyFailure"
| summarize WouldBeBlocked = count(), Apps = make_set(AppDisplayName, 10), Resources = make_set(ResourceDisplayName, 10),
    LastSeen = max(TimeGenerated)
    by UserPrincipalName, AuthenticationProtocol, OriginalTransferMethod
| order by WouldBeBlocked desc

Every account in the result is either a missed exception or a sign-in you want to stop. Add a missed account to an exception group or move its tool off device code flow, then check again until only unwanted sign-ins remain. Before enforcement, Microsoft also asks you to confirm that Teams devices still register and reauthenticate, and that the emergency access accounts remain excluded.

Step 6: Turn the policy on

Turn the policy on when the report-only results show only sign-ins you want to stop. In the portal, open the policy and move Enable policy from Report-only to On. In Microsoft Graph PowerShell, update the state alone and preview it first:

Connect-MgGraph -Scopes 'Policy.Read.All', 'Policy.ReadWrite.ConditionalAccess'

Update-MgIdentityConditionalAccessPolicy -ConditionalAccessPolicyId '33333333-3333-3333-3333-333333333333' -State 'enabled' -WhatIf

Drop -WhatIf to apply it. Microsoft's Graph reference says properties you leave out of an update keep their values or are recalculated. The change writes an Update Conditional Access policy record.

Align the Microsoft-managed policy

Microsoft says all applicable Conditional Access policies must be satisfied. An account excluded from your policy can still be blocked by the managed Block device code flow policy once Microsoft turns it on, unless you exclude it there too. We recommend one of two paths:

  • Use the managed policy as your block: add the emergency access and exception groups to its exclusions and turn it on. Check its target resources first: a managed policy accepts changes to its state and excluded identities only, so you can't add a Device Registration Service exclusion to it yourself.
  • Use your own policy: keep the policy from Step 4, which can exclude the Device Registration Service, and set the managed policy to Off. Microsoft suggests duplicating a managed policy when you need more changes than it allows.

Step 7: Block authentication transfer

If nobody needs to move a session from a PC to a phone with a QR code, block authentication transfer with a second policy. Microsoft's example uses the same assignments with Authentication transfer selected under Authentication Flows and the emergency access accounts excluded. Its authentication transfer article recommends report-only mode first, so the script creates this policy in report-only mode too:

.\New-EntraAuthFlowBlockPolicy.ps1 -DisplayName 'Block authentication transfer' -EmergencyAccessGroupId '11111111-1111-1111-1111-111111111111' -TransferMethod 'authenticationTransfer' -WhatIf

Review the results as in Step 5, then turn it on as in Step 6. In the sign-in logs, a session that started with authentication transfer shows Authentication transfer as its original transfer method.

Verify

Check the policy, a blocked test sign-in and a working exception.

Check Expected result
Get-EntraAuthFlowPolicyAudit.ps1 The block policy shows State enabled and BlocksAccess True, with no Report-only, Not all users or No group exclusions finding and no summary row
A device code sign-in by a test account outside the exception groups, for example az login --use-device-code The sign-in fails, and its sign-in log entry names the policy on the Conditional Access tab
A Teams device that uses a resource account from the exception group The device registers and signs in as before
The after-enforcement query in the Monitor section, the next day Only the device code sign-ins you expected

This read-only command shows the state, the flow and the grant of the policy. It needs Policy.Read.All:

Connect-MgGraph -Scopes 'Policy.Read.All'

Get-MgIdentityConditionalAccessPolicy -ConditionalAccessPolicyId '33333333-3333-3333-3333-333333333333' |
    Select-Object DisplayName, State,
        @{ Name = 'TransferMethods'; Expression = { $_.Conditions.AuthenticationFlows.TransferMethods } },
        @{ Name = 'Grant'; Expression = { $_.GrantControls.BuiltInControls -join ', ' } }
DisplayName            State   TransferMethods Grant
-----------            -----   --------------- -----
Block device code flow enabled deviceCodeFlow  block

Roll back

Every step here can be reversed; a deleted policy can be restored only for a limited time.

Change How to roll back Notes
Block policy turned on Set Enable policy to Report-only or Off in the portal, or run the command below Microsoft says a device may then need a fresh token before it works again
Block policy created Delete the policy You can restore a deleted Conditional Access policy within the 30-day soft-delete period
Managed policy set to Off Change its state again in the policy Microsoft lets you edit the state of a managed policy
Account added to an exception group Remove the member The account is back under the block
Connect-MgGraph -Scopes 'Policy.Read.All', 'Policy.ReadWrite.ConditionalAccess'

Update-MgIdentityConditionalAccessPolicy -ConditionalAccessPolicyId '33333333-3333-3333-3333-333333333333' -State 'enabledForReportingButNotEnforced' -WhatIf

Monitor and detect

After enforcement, alert on device code sign-ins outside your exceptions and on every change to the policy, because exceptions grow and policies change. Microsoft's Teams guidance asks you to review exception membership regularly and to alert on unexpected device code use by privileged users, emergency access accounts, unfamiliar apps or unexpected locations. Its security operations guide for applications rates successful device code sign-ins as low to medium risk, to investigate wherever no input-constrained device needs them.

Device code sign-ins after enforcement

The query below lists device code sign-ins by every account outside your approved list. A success means an exclusion or a gap let the flow through. A failure with error 53003 (BlockedByConditionalAccess) is the policy working, but Microsoft enforces Conditional Access after first-factor authentication. So a blocked device code sign-in suggests someone completed the first factor; ask the user where the code came from.

// After the block is on: device code sign-ins by accounts outside the approved list, successful or blocked.
// Needs the user sign-in logs in the workspace. In an alert rule, the rule's lookback window sets the time range.
let ApprovedAccounts = dynamic(["mtr-room01@corp.example.com", "mtr-room02@corp.example.com"]);
SigninLogs
| where AuthenticationProtocol == "deviceCode"
| where UserPrincipalName !in~ (ApprovedAccounts)
| extend Outcome = case(ResultType == "0", "Succeeded", ResultType == "53003", "Blocked by Conditional Access", "Failed")
| project TimeGenerated, UserPrincipalName, Outcome, ResultType, AppDisplayName, ResourceDisplayName, IPAddress,
    Location, ConditionalAccessStatus, CorrelationId
| order by TimeGenerated desc

Changes to the policy and its exceptions

The second query catches updates and deletions of the policy, with the old and new state and whether the exclusions changed, and membership changes in the exception groups. It reads the old and new policy JSON under TargetResources > modifiedProperties, the way Microsoft's Sentinel templates for disabled and report-only policies do. Activity names are matched without case, because those templates spell the update activity Update conditional access policy.

// Changes to the device code block policy and to its exception groups, from the Microsoft Entra audit log.
// Read-only. Replace the IDs with your policy ID and exception group IDs.
let PolicyId = "33333333-3333-3333-3333-333333333333";
let TeamsDeviceGroupId = "22222222-2222-2222-2222-222222222222";
let ApprovedToolGroupId = "44444444-4444-4444-4444-444444444444";
AuditLogs
| where TimeGenerated > ago(30d)
| where OperationName in~ ("Update Conditional Access policy", "Delete Conditional Access policy", "Add member to group", "Remove member from group")
| extend TargetText = tostring(TargetResources)
| where TargetText contains PolicyId or TargetText contains TeamsDeviceGroupId or TargetText contains ApprovedToolGroupId
| extend Actor = coalesce(tostring(InitiatedBy.user.userPrincipalName), tostring(InitiatedBy.app.displayName))
| extend OldPolicy = tostring(TargetResources[0].modifiedProperties[0].oldValue), NewPolicy = tostring(TargetResources[0].modifiedProperties[0].newValue)
| extend StateOld = extractjson("$.state", OldPolicy), StateNew = extractjson("$.state", NewPolicy)
| extend ExclusionsChanged = extractjson("$.conditions.users.excludeGroups", OldPolicy) != extractjson("$.conditions.users.excludeGroups", NewPolicy)
    or extractjson("$.conditions.users.excludeUsers", OldPolicy) != extractjson("$.conditions.users.excludeUsers", NewPolicy)
| project TimeGenerated, OperationName, Result, Actor, Target = tostring(TargetResources[0].displayName), StateOld, StateNew,
    ExclusionsChanged, CorrelationId
| order by TimeGenerated desc
Activity Why it matters Related pages
Successful device code sign-in outside the exceptions A gap in the policy, or tokens in an attacker's hands Rules for stolen tokens and phishing proxies
Device code sign-in blocked by Conditional Access Someone entered a code that the block stopped Rules for sign-ins blocked by Conditional Access
Add registered owner to device soon after a device code sign-in A device registered with the phished session, as in the Storm-2372 update Rogue device registration rules
Update Conditional Access policy, Delete Conditional Access policy The block was weakened, switched to report-only mode or removed Rules for weakened or deleted Conditional Access policies
Add member to group or Remove member from group on an exception group The flow was opened or closed for an account The second query

If a device code sign-in turns out to be phishing, revoke the user's sessions and refresh tokens at once. Microsoft's EvilTokens report notes that revocation often invalidates only refresh tokens, leaving existing access tokens active for up to an hour. Our risky users guide covers the investigation that follows.

What about AWS IAM Identity Center?

IAM Identity Center has the same risk in command-line sign-in. AWS's CLI documentation says the AWS CLI uses authorization code with PKCE by default from version 2.22.0, and device authorization in older versions or with --use-device-code. CloudTrail records the token exchange as a CreateToken event, and the OIDC API names the device code grant urn:ietf:params:oauth:grant-type:device_code.

Keep the CLI current and check every device code grant with our IAM Identity Center device code phishing rules. Our IAM Identity Center guide covers the wider move from IAM users.

Troubleshooting

Most problems come from a missing exception or from protocol tracking.

Symptom Cause Fix
A Teams device is blocked after the policy goes on Its resource account isn't in the exception group, or the Device Registration Service isn't excluded Add the account, exclude the resource, and check Original transfer method on the blocked sign-in
A user is blocked in an app that doesn't use device code flow The session started with device code flow and is protocol tracked Expected behavior; sign in again with a browser or broker
Sign-in fails with AADSTS530036 A refresh token from a device code session failed the authentication flow checks of a policy that covers all applications Delete the cached token and sign in again without device code flow
Device registration with device code flow fails Authentication flows policies that target all resources apply to the Device Registration Service Exclude Device Registration Service under Target resources
az login fails on a machine where it can't open a browser Azure CLI falls back to device code flow when it can't open a browser Sign in from a session with a browser or broker, or request a documented exception
A device still fails after the policy is set to report-only or off The device holds a token from the blocked session Sign in again to get a fresh token
The Graph script fails with a permissions error The policy API has a known permissions issue and may need several permissions Connect with all three scopes as a Conditional Access Administrator
A managed policy blocks an account you excluded The exception exists only in your own policy Exclude the groups from the managed policy too, or set it to Off if your policy covers the block

How Forestall helps

Forestall's CAP Audit compares your Conditional Access policies with a baseline of expected protections, and its Ineffective Policies view lists policies that protect nobody, report-only ones included. A device code block left in report-only mode shows up there. Each Conditional Access policy page restates the policy in plain language and points out risks such as a missing break-glass exclusion. The AZ_CAP_EXCLUDES edge records every exclusion, where unexpected exclusions are a finding, and Identity Attack Surface Management maps identities and trust relationships across hybrid environments without agents.

Frequently Asked Questions

What is device code flow?

Device code flow is Microsoft Entra ID's implementation of the OAuth 2.0 device authorization grant, defined in RFC 8628. A device without a browser, such as a meeting room system or a command-line tool, shows a short code. The user enters it on Microsoft's sign-in page from another device and signs in, and the device receives the tokens. By default the user has 15 minutes to complete the sign-in.

How does device code flow work?

In device code flow, the client asks Microsoft Entra ID's device code endpoint for a device code and a user code, then shows the user code with a verification URL. The user opens the URL on a phone or PC, enters the code and signs in. Meanwhile the client polls the token endpoint and receives an access token and a refresh token once the user has finished.

What does it mean to block device code flow?

Blocking device code flow means a Conditional Access policy with the authentication flows condition and the Block access grant refuses sign-ins that use the flow. Through protocol tracking, it also stops later token refreshes in a session that started with device code flow. Microsoft recommends blocking it wherever possible and allowing it only for documented cases, such as Teams device resource accounts.

Does blocking device code flow break Microsoft Teams Rooms?

Blocking device code flow can break Microsoft Teams Rooms, because some Teams devices use device code flow for first-time registration, reprovisioning and some reauthentication. Microsoft's guidance is to put the Teams device resource accounts in a persistent exception group and exclude that group and the Device Registration Service from the policy. Validate the result in report-only mode before you turn the policy on. Personal Teams devices need a documented, monitored exception.

Does MFA stop device code phishing?

No: in device code phishing the user signs in on Microsoft's genuine page and completes any MFA prompt, and the tokens then go to the session the attacker started. Microsoft Threat Intelligence describes attackers using the flow to circumvent traditional MFA protections. Microsoft also notes that because the sign-in page is real, the attack can be harder for users to recognize. Blocking the flow removes the path for everyone outside your exceptions.

Should I block authentication transfer too?

Block authentication transfer unless you have a documented business need for moving a session from a PC to a phone with a QR code. Microsoft's guidance recommends blocking it, because someone with access to one device could use the flow to reach resources on other devices, and it bypasses non-Microsoft mobile device management. The feature is in preview, as of November 2026. Use a separate policy and test it in report-only mode first.

References

Share This Article, Secure Your Friends!

See your identity exposure clearly.

Start with a 1-day Proof of Value in your own environment.