【问题标题】:EWS + MSAL and storing OAuth tokens for later useEWS + MSAL 并存储 OAuth 令牌以供以后使用
【发布时间】:2019-12-07 02:09:57
【问题描述】:

我需要有关如何检索存储的 MSAL 令牌的帮助,以便在我的应用程序的执行中重复使用它。

场景:

我正在关注this Microsoft demo,它展示了如何使用 MSAL 获取 Oauth2 令牌,以便在控制台应用程序中对 EWS 进行身份验证。它工作正常,每次运行应用程序时都会弹出一个交互式登录窗口以获取令牌。

我现在想在以后独立执行应用程序时使用相同的令牌(或其刷新令牌,如果原始令牌已过期)。

最终,我想实现一个应用程序,用户通过我的 Web UI 提供初始交互式 Oauth 登录,从那时起,我存储与 EWS 邮箱交互的后台应用程序的令牌,并在需要时执行刷新.

我正在尝试什么:

我一直在尝试理解基于本地文件的令牌缓存的“naive implementation”。我可以看到它正在创建一个本地文件,但是我怎样才能让它在以后的执行中检查这个文件,并使用它存储在那里的令牌。然后我找到了通往this MSAL extension library 的方法,但它没有文档,我什至无法适应它的测试。

我的代码:

static async System.Threading.Tasks.Task MainAsync(string[] args)
    {
        // Configure the MSAL client to get tokens
        var pcaOptions = new PublicClientApplicationOptions
        {
            ClientId = ConfigurationManager.AppSettings["appId"],
            TenantId = ConfigurationManager.AppSettings["tenantId"]
        };

        var pca = PublicClientApplicationBuilder
            .CreateWithApplicationOptions(pcaOptions).Build();
        TokenCacheHelper.EnableSerialization(pca.UserTokenCache); // added based on 'naive implementation'

        var ewsScopes = new string[] { "https://outlook.office.com/EWS.AccessAsUser.All" };

        try
        {
            // Make the interactive token request
            var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync(); // must have to change this to something else that is aware of the cache?

            // Configure the ExchangeService with the access token
            var ewsClient = new ExchangeService();
            ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
            ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);

            // Make an EWS call
            // ... do stuff in EWS ...
        }
    }

帮助代码(来自'naive implementation')

static class TokenCacheHelper
{
    public static void EnableSerialization(ITokenCache tokenCache)
    {
        tokenCache.SetBeforeAccess(BeforeAccessNotification);
        tokenCache.SetAfterAccess(AfterAccessNotification);
    }

    /// <summary>
    /// Path to the token cache
    /// </summary>
    public static readonly string CacheFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location + ".msalcache.bin3";

    private static readonly object FileLock = new object();


    private static void BeforeAccessNotification(TokenCacheNotificationArgs args)
    {
        lock (FileLock)
        {
            args.TokenCache.DeserializeMsalV3(File.Exists(CacheFilePath)
                    ? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath),
                                              null,
                                              DataProtectionScope.CurrentUser)
                    : null);
        }
    }

    private static void AfterAccessNotification(TokenCacheNotificationArgs args)
    {
        // if the access operation resulted in a cache update
        if (args.HasStateChanged)
        {
            lock (FileLock)
            {
                // reflect changesgs in the persistent store
                File.WriteAllBytes(CacheFilePath,
                                    ProtectedData.Protect(args.TokenCache.SerializeMsalV3(),
                                                            null,
                                                            DataProtectionScope.CurrentUser)
                                    );
            }
        }
    }
}

【问题讨论】:

    标签: .net oauth-2.0 azure-active-directory exchangewebservices msal


    【解决方案1】:

    我认为你想要的模式应该是:

    • 调用系统浏览器进行登录
    • 登录后返回非浏览器应用
    • 将生成的令牌存储在操作系统安全存储中

    这是针对桌面应用程序的 OAuth - 即使桌面进程没有 UI(对于控制台应用程序而言)。

    EWS 应用程序是否作为另一个应用程序的插件运行?如果是这样,您将需要使用桌面登录的环回变体。

    我有两个在线桌面示例可以帮助您理解问题 - 您应该能够很容易地运行它们:code-samples-quickstart

    我也有一些详细的文章从这里开始: desktop-apps-overview.

    我的代码在 Node.js 中。

    【讨论】:

      猜你喜欢
      • 2020-05-04
      • 2012-07-06
      • 1970-01-01
      • 2013-08-08
      • 2018-07-21
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多