如何静默获取访问令牌到用户订阅Azure Batch?

时间:2017-04-25 09:52:54

标签: azure active-directory azure-active-directory azure-batch

我正在开发项目,我们的服务在Azure Batch上以用户订阅模式运行计算(因为我们使用的是自定义图像)。我现在的代码完全正常工作,但它要求每次启动都提供用户凭据,以便在创建批处理池等之前登录Azure Active Directory应用程序。因为它将作为后台服务运行,所以我需要使用一些提供的用户静默登录,而无需弹出窗口要求用户登录。

我在Azure中注册了本机应用,并设置了对Azure Batch服务的访问权限,创建了Azure AD用户,并从中获取了所有ID和名称。

这是我现在使用的代码。

private const string AuthorityUri = "https://login.microsoftonline.com/common";
private const string BatchResourceUri = "https://batch.core.windows.net";

private const string BatchAccountEndpoint = "https://<BATCH SERVICE NAME>.westeurope.batch.azure.com";
private const string ClientId = "<AZURE APP GUID ID>";

...

public static async Task<string> GetAuthenticationTokenAsync()
{
    var authContext = new AuthenticationContext(AuthorityUri);

    //here it will throw exception about no token found in cache and to call AquireToken
    var authResult = await authContext.AcquireTokenSilentAsync(BatchResourceUri, ClientId, new UserIdentifier("<AD USER GUID ID>", UserIdentifierType.UniqueId));

    //this works fine, but show popup dialog for login
    /*var authResult = await authContext.AcquireTokenAsync(BatchResourceUri,
                                                            ClientId,
                                                            new Uri(RedirectUri),
                                                            new PlatformParameters(PromptBehavior.Auto));*/

    return authResult.AccessToken;
}

...

Func<Task<string>> tokenProvider = () => GetAuthenticationTokenAsync();


using (BatchClient batchClient = await BatchClient.OpenAsync(new BatchTokenCredentials(BatchAccountEndpoint, tokenProvider)))
{
    ...
}

使用AquireToken和弹出窗口进行登录的经典方式工作正常。我曾尝试使用AquireTokenSilent(如代码中所示),但我收到的错误是没有令牌缓存,需要调用AquireToken。

UserIdentifier中使用的Id是从Azure Active Directory用户刀片中获取的用户ID guid。

有谁知道,如何更新我的代码,以便我能够以指定用户静默登录Azure Batch,这是否可能?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

AcquireTokenSilent不适用于此用例。它将尝试从AcquireTokenAsync以前存储的缓存中获取令牌。

AcquireTokenAsync会弹出一个登录对话框,因此您也无法在批量应用中使用它。

使用certificateusername/password进行身份验证。

在第一个示例中,您需要使用

创建ClientAssertionCertificate
certCred = new ClientAssertionCertificate(clientId, cert);

然后将其用于AcquireTokenAsync

result = await authContext.AcquireTokenAsync(todoListResourceId, certCred);

另一个示例使用

创建UserPasswordCredential
var uc = new UserPasswordCredential(user, password);

然后以AcquireTokenAsync的方式稍微使用它:

authContext.AcquireTokenAsync(todoListResourceId, clientId, uc);

对于基于两种不同身份验证方法的令牌可以执行的操作存在一些限制。例如,使用EWS模拟的访问令牌需要使用证书方法。