2016-01-01 13 views
6

Sto utilizzando l'API REST di Azure per recuperare i dettagli sull'utilizzo della fatturazione e sui rapporti. Per acquisire il token utilizzando il metodo AcquireToken(), inizialmente ho utilizzato solo ID client che richiede quindi le credenziali utente nella finestra di accesso.L'API di utilizzo della fatturazione di Azure restituisce 401 Non autorizzato

Tuttavia, sto cercando approccio non-interattiva, quindi ho usato credenziali client in cui ho passato Id client e client chiave segreta.

Ma dà "server remoto restituisce un errore 401 non autorizzato"

Quando guardo in errore profondamente, ho trovato che dà l'errore "Il token di accesso è dal pubblico sbagliato o risorsa"

Per favore dammi qualsiasi soluzione con cui posso accedere all'API senza alcuna interazione da parte dell'utente.

Grazie in anticipo.

Ecco il mio codice:

{ 
    string token = GetOAuthTokenFromAAD(); 
    string requestURL = String.Format("{0}/{1}/{2}/{3}", 
        ConfigurationManager.AppSettings["ARMBillingServiceURL"], 
        "subscriptions", 
        ConfigurationManager.AppSettings["SubscriptionID"], 
        "providers/Microsoft.Commerce/RateCard?api-version=2015-06-01-preview&$filter=OfferDurableId eq 'MS-AZR-*****' and Currency eq 'INR' and Locale eq 'en-IN' and RegionInfo eq 'IN'"); 

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL); 

    request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token); 
    request.ContentType = "application/json"; 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    Console.WriteLine(String.Format("RateCard service response status: {0}", response.StatusDescription)); 
} 

public static string GetOAuthTokenFromAAD() 
{ 
     AuthenticationContext authenticationContext = new AuthenticationContext(string.Format("{0}/{1}",ConfigurationManager.AppSettings["ADALServiceURL"], ConfigurationManager.AppSettings["TenantDomain"])); 

     AuthenticationResult result = null; 
     ClientCredential uc = new ClientCredential(Client_Id, Secret_Key); 
     try 
     { 
      result = authenticationContext.AcquireToken("https://management.core.windows.net/", uc); 
     } 
     return result.AccessToken; 
} 

//App Config File 
<add key="ADALServiceURL" value="https://login.microsoftonline.com" /> 
<add key="ADALRedirectURL" value="http://*****-authentication.cloudapp.net" /> 
<add key="ARMBillingServiceURL" value="https://management.core.windows.net" /> 
<add key="TenantDomain" value="********.onmicrosoft.com" /> 
<add key="SubscriptionID" value="*******-****-****-****-********" /> 
<add key="ClientId" value="*******-****-****-****-********" /> 
+0

Si prega di condividere il proprio codice e anche le impostazioni per l'applicazione creata in Azure AD. –

+0

Aggiunto nel post. – Tejas

+0

Una domanda rapida: hai aggiunto l'autorizzazione per eseguire le operazioni dell'API di gestione dei servizi durante la configurazione dell'applicazione in Azure AD? –

risposta

1

Update: Ho anche fornito questi metodi come riutilizzabile autenticazione Helper Class Library. È possibile trovare lo stesso a questo link: Azure Authentication - Authenticating any Azure API Request in your Application

Metodo 1: di utilizzare l'approccio della password in modo non interattivo è necessario prima seguire la sezione del post qui sotto "l'autenticazione con la password - PowerShell": Authenticating a service principal with ARM

Quindi utilizzare lo snippet di codice seguente per recuperare il token.

var authenticationContext = new AuthenticationContext(String.Format("{0}/{1}", 
                   ConfigurationManager.AppSettings["ADALServiceURL"], 
                   ConfigurationManager.AppSettings["TenantDomain"])); 
     var credential = new ClientCredential(clientId: "11a11111-11a1-111a-a111-1afeda2bca1a", clientSecret: "passwordhere"); 
     var result = authenticationContext.AcquireToken(resource: "https://management.core.windows.net/", clientCredential: credential); 

     if (result == null) 
     { 
      throw new InvalidOperationException("Failed to obtain the JWT token"); 
     } 

     string token = result.AccessToken; 

     return token; 

alternativa (metodo 2), è anche possibile utilizzare il metodo certificato. In tal caso, utilizzare lo stesso link come sopra ma seguire la sezione "Autentica con certificato - PowerShell" da quel collegamento. Quindi utilizzare lo snippet di codice seguente per scaricare il token in modo non interattivo:

var subscriptionId = "1a11aa11-5c9b-4c94-b875-b7b55af5d316"; 
     string tenant = "1a11111a-5713-4b00-a1c3-88da50be3ace"; 
     string clientId = "aa11a111-1050-4892-a2d8-4747441be14d"; 

     var authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenant)); 

     X509Certificate2 cert = null; 
     X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); 
     string certName = "MyCert01"; 

     try 
     { 
      store.Open(OpenFlags.ReadOnly); 
      var certCollection = store.Certificates; 
      var certs = certCollection.Find(X509FindType.FindBySubjectName, certName, false); 
      //var certs = certCollection.Find(X509FindType.FindBySerialNumber, "E144928868B609D35F72", false); 
      if (certs == null || certs.Count <= 0) 
      { 
       throw new Exception("Certificate " + certName + " not found."); 
      } 
      cert = certs[0]; 
     } 
     finally 
     { 
      store.Close(); 
     } 

     var certCred = new ClientAssertionCertificate(clientId, cert); 
     var token = authContext.AcquireToken("https://management.core.windows.net/", certCred); 
     var creds = new TokenCloudCredentials(subscriptionId, token.AccessToken); 
     //var client = new ResourceManagementClient(creds); 
     return token.AccessToken; 
Problemi correlati