AcquireTokenSilentAsync无法正常工作,因为ConfidentialClientApplication没有用户

时间:2018-05-02 14:29:24

标签: c# asp.net owin microsoft-graph openid-connect

我遇到了AcquireTokenSilentAsync方法的问题,并希望有人能帮助我。

在下面的方法中,我尝试使用AcquireTokenSilentAsync方法,以便稍后可以使用它来调用Microsoft图形api。遗憾的是ConfidentialClientApplication的用户属性为空,因此cca.AcquireTokenSilentAsync失败,因为它需要调用cca.Users.First()参数中的第一个用户。

public async Task<string> GetUserAccessTokenAsync()
    {
        string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
        HttpContextWrapper httpContext = new HttpContextWrapper(HttpContext.Current);
        TokenCache userTokenCache = new SessionTokenCache(signedInUserID, httpContext).GetMsalCacheInstance();

        ConfidentialClientApplication cca = new ConfidentialClientApplication(
            appId, 
            redirectUri,
            new ClientCredential(appSecret),
            userTokenCache,
            null);

        try
        {
            AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes.Split(new char[] { ' ' }), cca.Users.First());
            return result.AccessToken;
        }

        // Unable to retrieve the access token silently.
        catch (Exception)
        {
            HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties() { RedirectUri = "/" },
                OpenIdConnectAuthenticationDefaults.AuthenticationType);

            throw new ServiceException(
                new Error
                {
                    Code = GraphErrorCode.AuthenticationFailure.ToString(),
                    Message = Resource.Error_AuthChallengeNeeded,
                });
        }
    }
}

我不确定为什么ConfidentialClientApplication不包含任何用户,因为应用程序开头的登录工作正常。我只在启动时使用UseCookieAuthenticationUseOpenIdConnectAuthentication

我希望有人能帮我解决这个问题!

0 个答案:

没有答案