使用服务主体凭据获取第三方应用程序的访问令牌

时间:2019-02-05 11:50:46

标签: azure-active-directory

我试图在我的AAD租户中使用Azure AD服务主体来获取Azure AD应用程序代理服务的访问令牌,以用于注册新的连接器。服务主体在我的租户中具有必需的权限才能执行此操作。基本上,我试图采用以下代码来支持使用主体进行身份验证,而不是进行交互式身份验证流程。这将允许从安全存储中获取服务主体信息和机密/证书,并将其用于自动化管道。但是,我的技能已耗尽!有谁知道该怎么做?

{
"count": false,
 "facets": [],
 "filter": "search.ismatch('6','CataloguesIds')",
 "queryType": "full",
 "scoringParameters": [],
 "search": "pier%C5%9Bcionek*",
 "searchMode": "any",
 "select": "Id,Name"
 }

我的尝试总是在AcquireTokenAsync步骤失败。

谢谢!

1 个答案:

答案 0 :(得分:0)

当您要使用密码对SP进行身份验证时,应考虑使用AuthenticationContext重载(请参见文档here):

public System.Threading.Tasks.Task<Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult> AcquireTokenAsync (string resource, Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential clientCredential);

// Sample code
var authContext = new AuthenticationContext("<authority uri>");
var clientCreds = new ClientCredential("<app id associated to sp>", "<app secret>");
authContext.AcquireTokenAsync("<resource>", clientCreds);

另一方面,如果要使用证书对SP进行身份验证,则应考虑使用AuthenticationContext的此重载(请参见文档here):

public System.Threading.Tasks.Task<Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult> AcquireTokenAsync (string resource, Microsoft.IdentityModel.Clients.ActiveDirectory.IClientAssertionCertificate clientCertificate);

// Sample code
// fetch certificate first
var storeName = StoreName.My;
var storeLocation = StoreLocation.LocalMachine; // if cert lives in local machine store, code needs to run as administrator
string certName = "<my cert subject name>"; // e.g. "CN = myspcertficate"
X509Store store = new X509Store(storeName, storeLocation);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = store.Certificates;
X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, false);
X509Certificate2 cert = signingCert.OfType<X509Certificate2>().OrderByDescending(c => c.NotBefore).FirstOrDefault();
store.Close();
if (cert != null)
{
    var authContext = new AuthenticationContext("<authority uri>");
    authContext.AcquireTokenAsync("<resource>", "<app id associated to sp>", cert);
}