通过图表获取所有用户及其上次登录 API

Getting all users and their last login via graph API

我正在尝试导出所有用户数据,包括上次登录日期。我正在关注这篇文章:

https://morgantechspace.com/2021/09/find-last-login-date-for-all-azure-ad-users-using-powershell.html

通过使用此调用: https://graph.microsoft.com/beta/users?$select=displayName,signInActivity

PS:

$Url = "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token"

# Add System.Web for urlencode
Add-Type -AssemblyName System.Web

# Create body
$Body = @{
    client_id = $AppId
    client_secret = $AppSecret
    scope = $Scope
    grant_type = 'client_credentials'
}

# Splat the parameters for Invoke-Restmethod for cleaner code
$PostSplat = @{
    ContentType = 'application/x-www-form-urlencoded'
    Method = 'POST'
    # Create string by joining bodylist with '&'
    Body = $Body
    Uri = $Url
}

# Request the token!
$Request = Invoke-RestMethod @PostSplat

$ApiUrl = "https://graph.microsoft.com/beta/users?$select=displayName,signInActivity"

$Header = @{
    Authorization = "$($Request.token_type) $($Request.access_token)"
}

While ($ApiUrl -ne $Null) #Perform pagination if next page link (odata.nextlink) returned.
{
    # Fetch all security alerts
    $SecurityAlertsRequest = Invoke-RestMethod -Uri $ApiUrl -Headers $Header -Method Get -ContentType "application/json"

    $SecurityAlerts = $SecurityAlertsRequest.Value

    foreach($User in $SecurityAlerts){
         if($User.signInActivity.lastSignInDateTime) { 

            $test = [DateTime]$User.signInActivity.lastSignInDateTime 

    } Else {$null}


    }

    $ApiUrl=$SecurityAlertsRequest.'@odata.nextlink'
}

$SecurityAlerts

我通过应用注册连接:

但是,所有用户的 signInActivity 始终为 null。是否不可能让所有用户都具有图表 API 包括上次登录?

两个关键点是,首先你需要将AuditLog.Read.All权限范围添加到你的应用程序权限中。其次,SignInActivity 是 Microsoft Graph SDK API“测试版”的一部分。您必须在连接之前将您的 Microsoft Graph 配置文件更改为“测试版”才能访问 API 的测试版 我发现使用新的 Microsoft Graph PowerShell SDK PowerShell 模块更容易获取此信息:

Select-MgProfile -Name "beta"
Connect-MgGraph -Scopes 'AuditLog.Read.All'
$user = Get-MgUser -UserId '123-...-abc123' -Property 'SignInActivity'
$user.SignInActivity.LastSignInDateTime

MS Graph REST URL 中的 $ 需要作为查询字符串的一部分。您需要使用反引号 ` 将其转义,或使用单引号:

$ApiUrl = "https://graph.microsoft.com/beta/users?`$select=displayName,signInActivity"