AcquireTokenSilent always Failed to acquire token silently

杀马特。学长 韩版系。学妹 提交于 2019-11-30 17:43:09

The issue was that basically I was using Common Authority https://login.windows.net/common/oauth2/authorize in my App. It works for AcquireTokenByAuthorizationCode() but not for AcquireTokenSilent().

So I needed it to save the TenantId when call AcquireTokenByAuthorizationCode() and an authority use an authority like https://login.windows.net/<tenant ID>/oauth2/authorizewhen call AcquireTokenSilent(). This way the same code above works.

vibronet

I don't understand the call:

authContext.AcquireTokenSilent(
    _authority,
    _clientCredential,
    new UserIdentifier(companyId.ToString(), UserIdentifierType.UniqueId)
).AccessToken;

The UserIdentifier must match the value in the cache, and CompanyID does not sound like any of the identifier you get back for the token.

Please take a look at the sample I pointed you to on the other thread, and specifically on the identifier used in call to AcquireTokenSilent in https://github.com/AzureADSamples/WebApp-WebAPI-OpenIDConnect-DotNet/blob/master/TodoListWebApp/Controllers/TodoListController.cs

You don't get to choose which identifier to use in that call, that is determined by what claims AAD issues. The only identifiers you can choose are at the cache instance level, not in individual AcquireToken* calls.

Check if token is existing in cache else sign out and ask user to sign in.

AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                        new NaiveSessionCache(userObjectID));
                    if (authContext.TokenCache.Count == 0)
                    {
                        authContext.TokenCache.Clear();
                        CosmosInterface.Utils.AuthenticationHelper.token = null;
                        HttpContext.GetOwinContext().Authentication.SignOut(
                            OpenIdConnectAuthenticationDefaults.AuthenticationType,
                            CookieAuthenticationDefaults.AuthenticationType);
                    }

I had the same issue in ASPNetCore (1.0) and the reason was that I wasn't storing the authentication token after logging in. I solved it by adding OnAuthorizationCodeReceived in the Startup class and changing my Response ype to ResponseType = OpenIdConnectResponseType.CodeIdToken.

Hope it helps.

Sample: https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore/blob/aspnet10/WebApp-WebAPI-OpenIdConnect-DotNet/Startup.cs#L100

This is an old question - but for me, I needed to clear my cookies on the client and then it forced the browser to re-auth and everything was fine again.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!