首页 文章

使用Azure AD多租户openID身份验证获取访问令牌

提问于
浏览
2

我按照示例代码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 . 我失踪了什么?

1 回答

  • 1

    绝对 . 查看https://github.com/AzureADSamples/WebApp-WebAPI-MultiTenant-OpenIdConnect-DotNet,它已经's like the sample you'一直在使用,但另外还有访问令牌获取和使用你要问的问题 . 另请注意,AcquireTokenSilent只有在缓存中有令牌时才能工作 - 直接使用或刷新 . FInally:当您要求令牌时,您必须同时指定要为其提供令牌的资源的ID以及执行请求的应用程序的clientID . 在您的代码中,您似乎使用了目标应用程序的clientID . 请参阅上面链接的示例,它显示了在此场景中使用的确切模式 .

相关问题