2016-11-07 50 views
0

我試圖使用C#.NET SDK獲取我的一個Web應用程序的配置。我想使用Azure AD應用程序而不是管理證書(我之前已經開始工作)。嘗試使用Azure .NET SDK獲取配置的異常

我有以下代碼:

var subscriptionId = "<subscription-guid>"; 
var appId = "<app-guid>"; 
var appKey = "<app-key>"; 
var tenantId = "<tenant-guid>"; 

var context = new AuthenticationContext("https://login.windows.net/" + tenantId); 
ClientCredential clientCredential = new ClientCredential(appId, appKey); 
var tokenResponse = context.AcquireTokenAsync("https://management.core.windows.net/", clientCredential).Result; 
var accessToken = tokenResponse.AccessToken; 

var myWebspace = "<my-webspace>"; 
var myWebsite = "<my-website>"; 

var client = new WebSiteManagementClient(new TokenCloudCredentials(subscriptionId, accessToken)); 
var config = client.WebSites.GetConfigurationAsync(myWebspace, myWebsite).Result; 

...但它是扔在最後一行出現以下錯誤:

Microsoft.WindowAzure.CloudException 
ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription. 

出了什麼問題?我已創建的應用程序,並給出了以下權限:

的Windows Azure服務管理

應用程序的權限:0

委託權限:1

訪問Azure的服務管理爲組織中的用戶(預覽)

Windows Azure Active Directory

應用權限:0

委託權限:1點

登錄和讀取用戶簡檔

預先感謝

克里斯

+0

請參閱本主題爲你的錯誤的可能原因得到:http://stackoverflow.com/questions/35190866/error-making-azure-management-library-api-call-when-authenticating-with-azure-ac –

+0

有沒有關於這個線程的日期? –

回答

0

作爲拉夫在另一個SO thread提及。我們可以切換到Azure資源管理器API。另一個非常重要的事情是,我們還需要創建服務主體來訪問資源。我們可以使用Azure PowerShell命令輕鬆完成。有關如何在Azure AD中註冊Web應用程序並創建服務主體的更多詳細步驟請參閱article

New-AzureRmRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $app.ApplicationId.Guid 

Microsoft.Azure.Management.WebSites SDK實現WebApp資源管理API。這是一個預發佈版本。 以下是我的代碼示例:

var subscriptionId = "Your subscription Id"; 
var appId = "Application Id"; 
var appKey = "secret key"; 
var tenantId = "tenant id"; 
var serviceCreds = ApplicationTokenProvider.LoginSilentAsync(tenantId, appId, appKey).Result; 
var webClient = new WebSiteManagementClient(serviceCreds) { SubscriptionId = subscriptionId }; 
var result = webClient.Sites.GetSiteConfigWithHttpMessagesAsync("ResourceGroup Name", "Web App name").Result; 

包文件:

<?xml version="1.0" encoding="utf-8"?> 
<packages> 
    <package id="Microsoft.Azure.Management.Websites" version="1.3.2-preview" targetFramework="net452" /> 
    <package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="2.28.1" targetFramework="net452" /> 
    <package id="Microsoft.Rest.ClientRuntime" version="2.3.1" targetFramework="net452" /> 
    <package id="Microsoft.Rest.ClientRuntime.Azure" version="3.1.0" targetFramework="net452" /> 
    <package id="Microsoft.Rest.ClientRuntime.Azure.Authentication" version="2.2.4.1-preview" targetFramework="net452" /> 
    <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net452" /> 
</packages> 

演示測試結果:

​​