Azure AD:user_interaction_required 验证本机应用程序时出现问题

Azure AD: user_interaction_required issue when authenticating a native application

我有来自 Office 365 的 Exchange Online 和一个邮箱,我需要通过使用托管 EWS 的控制台 C# 应用程序访问此邮箱。要求是控制台应用程序应该使用 OAuth 身份验证来访问 Exchange Online。

我设置了 Azure AD,并在那里创建了一个应用程序,收到了 clientid 和重定向 uri。我已授予该应用程序的完全权限 - 请查看下面的屏幕截图:

我正在使用 .NET 的 Active Directory 身份验证库(NuGet 的最新版本)来颁发令牌,但在获取令牌时遇到问题 运行...

我的代码是:

AuthenticationContext authenticationContext = new AuthenticationContext("https://login.windows.net/rsoftgroup.onmicrosoft.com", false);
AuthenticationResult authenticationResult = null;

try
{
    var authenticationTask = authenticationContext.AcquireTokenAsync(
        "outlook.office365.com", 
        "c4fa7d60-df1e-4664-a8f8-fb072d0bb287", 
        new Uri(redirectUri), 
        new PlatformParameters(PromptBehavior.Never)
    );

    authenticationTask.Wait();
    authenticationResult = authenticationTask.Result;
    exchangeService.Credentials = new OAuthCredentials(authenticationResult.AccessToken);
}
catch (AdalException)
{
    // Exception occured on the authentication process. 
}

我收到 AdalException 消息:“user_interaction_required:遇到两种情况之一:1. PromptBehavior.Never 标志已通过,但无法遵守约束,因为需要用户交互。2. 静默 Web 身份验证期间发生错误,导致 http 身份验证流程无法在足够短的时间内完成"

有人可以帮我解决吗?

我需要 OAuth 身份验证在没有用户交互的情况下工作,因为这将是一个命令行应用程序...

非常感谢任何建议。

您的应用程序仍然需要作为某些用户进行身份验证,目前如果您查看您的代码,您不会因为 PromptBehavior.Never 而进行身份验证,并且您没有指定任何用户凭据并使用隐式身份验证流程例如 http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/

对于您要进行身份验证的标准控制台应用程序(例如,当应用程序为 运行 时要求提供凭据)我会使用带外调用 urn:ietf:wg:oauth:2.0:oob(然后您不需要重定向端点)并将代码设置为提示 eg

AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/Common");

var authenticationTask = ac.AcquireTokenAsync(
"https://graph.windows.net",
"5471030d-f311-4c5d-91ef-74ca885463a7",
new Uri("urn:ietf:wg:oauth:2.0:oob"),
new PlatformParameters(PromptBehavior.Always)
).Result;

Console.WriteLine(authenticationTask.AccessToken);

当您 运行 控制台应用程序 windows 和 ADAL 库将处理管道并显示正确的身份验证提示并取回令牌时,您将获得减少攻击面而不是提示的好处在您的代码中获取您自己的凭据(或作为参数等)

正如 Venkat 评论所建议的那样,如果您不需要使用 EWS(例如,没有现有的代码库投资等),那么如果您构建守护程序类型的应用程序,那么使用 REST 端点可能是更好的解决方案,因为您可以利用它身份验证流程的类型,例如 https://blogs.msdn.microsoft.com/exchangedev/2015/01/21/building-daemon-or-service-apps-with-office-365-mail-calendar-and-contacts-apis-oauth2-client-credential-flow/