如何在客户端c#应用中使用Outlook REST API处理OAuth

本文关键字:Outlook REST API OAuth 处理 客户端 应用 | 更新日期: 2023-09-27 18:11:48

我正试图实现在客户端(编辑:安装Win10 UWP)应用程序中解释的内容,用于Outlook.com用户(没有O365,没有Azure)。正如邮件API参考中所解释的那样,当前的客户端库还没有准备好与常规Outlook.com用户和v2应用程序模型一起使用,因此我很想学习如何直接从客户端应用程序调用REST API。

具体来说,一个c#代码示例如何处理登录和权限请求操作将是非常感激的。此刻我知道如何使用System.Net.Http.HttpClient发送GET请求与指定的范围,以及如何打开web浏览器,让用户登录,但在他们授予许可,什么也不会发生,因为浏览器不知道热处理重定向的uri,这似乎是一个标准为每一个安装程序。因此我不知道如何接收响应消息的授权代码在我的应用程序。

谁能给像我这样对这种事情不熟悉的人解释一下如何处理这种情况?

编辑:正如我上面所说的,我正试图在一个安装的应用程序上工作,而不是一个web应用程序。当然,问题的底层逻辑是相同的,但我可以使用的库可能不是。具体来说,我正在开发一个Windows 10 UWP应用程序。

如何在客户端c#应用中使用Outlook REST API处理OAuth

dev.outlook.com上的教程适用于v2模型和Outlook.com。客户端库可以很好地与Outlook.com一起工作。发布的ADAL版本不支持v2 OAuth模型。Azure团队已经发布了一个"实验性"库,并且邮件API的客户端库也可以使用它。

这是一个不使用浏览器登录的示例。我们将使用outlook api和microsoftgraph来实现。我们必须先登录并获得令牌。

public class AccessTokenModel
    {
        [JsonProperty("access_token")]
        public string AccessToken { get; set; }
    }
public static string GetToken()
            {
                using (HttpClient client = new HttpClient())
                {
                client.BaseAddress = new Uri("https://login.microsoftonline.com");
                var content = new FormUrlEncodedContent(new[]
                {
                new KeyValuePair<string, string>("client_id", 'yourAppId'),
                new KeyValuePair<string, string>("client_secret", 'yourAppPassword'),
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", "emailAddress"),
                new KeyValuePair<string, string>("password", "emailPassword"),
                new KeyValuePair<string, string>("resource", "https://graph.microsoft.com"),
                new KeyValuePair<string, string>("scope", "openid")
                });
                var result = client.PostAsync($"/common/oauth2/token", content);
                var resultContent = result.Result.Content.ReadAsStringAsync();
                var model = JsonConvert.DeserializeObject<AccessTokenModel>(resultContent.Result);
                return model.AccessToken;
            }
        }

然后我们可以使用outlook api提供的服务