首页 > 解决方案 > AcquireTokenSilentAsync 无法正常工作,因为 ConfidentialClientApplication 没有用户

问题描述

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

在下面的方法中,我尝试使用该AcquireTokenSilentAsync方法,以便以后可以使用它来调用 Microsoft graph api。不幸的是,Users 的属性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不包含任何用户,因为应用程序开始时的登录工作正常。我只在启动时使用UseCookieAuthentication和。UseOpenIdConnectAuthentication

我希望任何人都可以帮助我解决这个问题!

标签: c#asp.netowinmicrosoft-graph-apiopenid-connect

解决方案


推荐阅读