使用无人值守的用户/密码创建Microsoft Graph GraphServiceClient

Ada*_*Ada 9 c# microsoft-graph

我正在创建一个使用Microsoft Graph API连接到Microsoft Graph的控制台应用程序(如https://github.com/microsoftgraph/console-csharp-connect-sample所示)。一切工作正常,但我想知道是否存在一种方法可以验证用户身份(当我已经知道其用户名/密码时)而无需他们在界面上显示的“ Sing in your account”窗口中手动输入其凭据。桌面。这个想法基本上是在无人值守的情况下运行应用程序,因此用户无需在应用程序启动时输入其凭据。我找不到与此主题相关的任何信息。那有可能吗?

编辑

在跟踪@DanSilver发布的关于没有用户访问的链接之后,我尝试了该链接中建议的示例(https://github.com/Azure-Samples/active-directory-dotnet-daemon-v2)。尽管那是一个MVC应用程序,它迫使用户进行身份验证(正是我要避免的身份),但我还是设法在控制台应用程序中使用了该示例中的部分身份验证代码。通过对https://login.microsoftonline.com/myTenantId/adminconsent的请求为应用程序手动授权后, 我可以在无需用户交互的情况下连接到Graph的控制台应用程序中创建GraphServiceClient。因此,我将答案标记为有效。万一有人处于相同的情况下,则将GraphServiceclient创建为:

GraphServiceClient graphServiceClientApplication = new GraphServiceClient("https://graph.microsoft.com/v1.0", new DelegateAuthenticationProvider(
    async (requestMessage) =>
    {
        string clientId = "yourClientApplicationId";
        string authorityFormat = "https://login.microsoftonline.com/{0}/v2.0";
        string tenantId = "yourTenantId";
        string msGraphScope = "https://graph.microsoft.com/.default";
        string redirectUri = "msalXXXXXX://auth"; // Custom Redirect URI asigned in the Application Registration Portal in the native Application Platform
        string clientSecret = "passwordGenerated"; 
        ConfidentialClientApplication daemonClient = new ConfidentialClientApplication(clientId, String.Format(authorityFormat, tenantId), redirectUri, new ClientCredential(clientSecret), null, new TokenCache());
        AuthenticationResult authResult = await daemonClient.AcquireTokenForClientAsync(new string[] { msGraphScope });
        string token = authResult.AccessToken;
        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);                            
    }                
));
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 4

一种想法是使用“仅限应用程序”授权流程。这个想法是,您可以让长时间运行的应用程序无需用户身份验证即可访问 Microsoft Graph。主要区别在于,它不是授予特定用户访问权限的访问令牌,而是授予您的应用程序对您事先同意的资源的访问权限。将不会出现用户登录对话框,您可以通过编程方式获取访问令牌来调用 Graph API。

要重申这些令牌不适用于特定用户,请考虑向“ https://graph.microsoft.com/v1.0/me ”发出 GET 请求。这将返回错误,因为访问令牌不是针对特定用户的,并且“me”没有任何意义。请求应使用完整的用户 ID“如 graph.microsoft.com/users/someuser@contosos.com”发送。

有关这方面的更多信息,请参阅无需用户文档即可获取访问权限页面。

另一个想法是让用户在第一次使用您的应用程序时进行身份验证,然后存储刷新令牌。这些令牌的寿命更长(几个月 IIRC),然后您无需在每次应用程序运行时提示用户同意。刷新令牌可以兑换为有效期为 60 分钟的访问令牌,这些令牌可用于代表用户调用 Graph API。

有关刷新令牌的更多信息:https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_user#5-use-the-refresh-token-to-get-a-new-access-token