【问题标题】:Get Access token with Azure AD multi-tenant openID authentication使用 Azure AD 多租户 openID 身份验证获取访问令牌
【发布时间】:2015-11-18 02:42:03
【问题描述】:

我按照示例代码 here 创建了一个具有 Azure AD 多租户 OpenID 身份验证的 MVC Web 应用程序。我使用以下代码让用户登录。

public void SignIn()
{
    if (!Request.IsAuthenticated)
    {
        HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
    }
}

现在我需要发送一个受 Azure AD 保护的 Web api 调用。目前,在我发送请求之前,我使用 ADAL 库要求用户再次登录并获取访问令牌,如下所示。

AuthenticationContext ac = new AuthenticationContext(authority);
AuthenticationResult ar = ac.AcquireToken(resourceID, clientID, redirectURI, PromptBehavior.Always); 
string accessToken = ar.AccessToken;

但是,由于 MVC 中使用的身份验证(如果用户来自我的 AD)与用于保护 web api 的身份验证相同。我想知道是否有办法在用户使用此 openID 身份验证登录时获取访问令牌,以便我可以跳过 ADAL 的第二次登录?

更新: 按照 vibronet 的回答,我正在尝试使用以下代码来获取令牌:

string authority = "https://login.windows.net/ucdavisprojecthotmail.onmicrosoft.com";

ClientCredential clientcred = new ClientCredential(clientId, appKey);
AuthenticationContext authContext = new AuthenticationContext(authority);
AuthenticationResult result = authContext.AcquireTokenSilent(resourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

这里,此代码用于 MVC Web 应用程序,clienId 和 appKey 是我要调用的 Web API 的 clientID 和密钥。 resoureID 是在 Azure 门户中获取的 Web API 的 APP ID URI。

但是,我收到此错误:无法以静默方式获取令牌。调用方法 AcquireToken。有什么我遗漏的吗?

【问题讨论】:

    标签: authentication azure azure-active-directory


    【解决方案1】:

    当然。查看https://github.com/AzureADSamples/WebApp-WebAPI-MultiTenant-OpenIdConnect-DotNet,它就像您一直在使用的示例,但另外还有您询问的访问令牌获取和使用。另请注意,AcquireTokenSilent 只有在缓存中有令牌时才能工作 - 可以直接使用或刷新。最后:当你请求一个令牌时,你必须指定你想要一个令牌的资源的 ID,以及执行请求的应用程序的 clientID。在您的代码中,您似乎使用了目标应用程序的 clientID。请参考我上面链接的示例,它显示了在这种情况下要使用的确切模式。

    【讨论】:

    • 检查您提供的示例代码后,我知道我需要使用 AcquireTokenSilent 方法。在示例中,AuthenticationContext 是使用这样的缓存构造的:AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", tenantID), new EFADALTokenCache(signedInUserID));。在示例代码中,我似乎需要处理 db。假设我根本不需要多租户,我只需要使用我的 AD。有没有更简单的方法来构建令牌缓存而不与 db 交互?
    • 您可以使用任何您喜欢的持久层构建缓存。例如,请参阅github.com/AzureADSamples/WebApp-WebAPI-OpenIDConnect-DotNet,其中缓存保存在会话中。缓存并不是真正用于处理多租户,只要您想保留访问令牌,就需要它。
    • 没有这个缓存我能拿到token吗?
    • 是的,但是你必须在每次请求时继续要求它
    • 我尝试使用 AcquireTokenSilent 但这不起作用。我已经更新了这个问题。请看一看。谢谢!
    猜你喜欢
    • 2020-08-26
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    相关资源
    最近更新 更多