简体   繁体   中英

Azure - Authenticating Service Management Requests

I need to perform few Azure SQL operations. I have an Azure AD native application. I'm using first approach from following article to aquire the token.

https://msdn.microsoft.com/en-us/library/azure/ee460782.aspx

Now following this article, I'm using the above token to perform the db operation.

static void HttpPost(string sourceDb, string targetDb, string pointInTime)
        {
            var client = new HttpClient();
            string uri = "https://management.core.windows.net:8443/" + AzureSubscriptionId + "/services/sqlservers/servers/" + AzureSqlServerName + "/restoredatabaseoperations";
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
            request.Headers.Add("Authorization", "Bearer " + accessToken);
            request.Headers.Add("x-ms-version", "2012-03-01");

            string payload = File.ReadAllText("Resources\\Backup.xml");
            payload = payload.Replace("$SourceDb", sourceDb);
            payload = payload.Replace("$TargetDb", targetDb);
            payload = payload.Replace("$PointInTime", pointInTime);
            request.Content = new StringContent(payload, Encoding.UTF8, "application/xml");

            HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult();
            if (response.Content != null)
            {
                string ss = response.Content.ReadAsStringAsync().Result;
            }
        }

But the error I receive is:

"<Error xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Code>AuthenticationFailed</Code><Message>A security token exception occured for the received JWT token.</Message></Error>"

According to you mentioned Create Database Restore Request (Classic) REST API , this command is used for classic deployment model. We should use the new REST API, and it is also mentioned in your mentioned document.

You should use the newer Resource Manager based REST API commands located here.

We could use the ARM REST Create or Update DataBase API. About how to get the token, we need to to registry AD App and assign role to application, more info please refer to official document . I send the http request from fiddler and it works correctly for me. Header and body info please refer to the screenshot.

在此处输入图片说明

在此处输入图片说明

Body info:

{
  "properties": {
    "edition": "Standard",
    "requestedServiceObjectiveName": "S1",
    "sourceDatabaseId": "/subscriptions/{your subscriptionId}/resourceGroups/{ResourceGroup}/providers/Microsoft.Sql/servers/{servername}/databases/sourcedatabasename",
    "createMode": "PointInTimeRestore",
    "restorePointInTime": "2017-02-09T10:28:20.21+08:00" //source database restorePointTime
  },
  "location": "East Asia",
  "tags": {}
}

We also can use Microsoft Azure SQL Management Library for .NET to that. SqlMgmtClient.Databases.CreateOrUpdate(resourceGroupName, serverName, databaseName, DatabaseCreateOrUpdateParameters) ;

We could refer to the tutorial to get started. I do a demo for it. More details please refer to the following steps

1.Create a console app and install the required libraries (detail refer to tutorial )

2.After registry an application, we could get tenantId, applicationId, SecretKey, then with subscriptionId to get the authentication token.

3.Create SqlManagementClient object with token

var _sqlMgmtClient = new SqlManagementClient(new TokenCloudCredentials(_subscriptionId, _token.AccessToken));

4.Create DatabaseCreateOrUpdateParameters according to our requirement. Take restore database from a source database for example:

 CreateMode = DatabaseCreateMode.PointInTimeRestore, //craete mode from pointtimerestore
 Edition = databaseEdition,
 SourceDatabaseId = "/subscriptions/subscriptionId/resourceGroups/groupname/providers/Microsoft.Sql/servers/AzureSQlname/databases/databaseName", //source database Id
 RestorePointInTime  = DateTime.Parse("2017-02-09T02:28:20.21Z"), //resore point Time
 RequestedServiceObjectiveName = "S1"
  1. run the demo and check from the portal.

    在此处输入图片说明

    在此处输入图片说明

democode:

       static void Main(string[] args)
        {
            _token = GetToken(_tenantId, _applicationId, _applicationSecret);
            Console.WriteLine("Token acquired. Expires on:" + _token.ExpiresOn);
            // Instantiate management clients:
            _resourceMgmtClient = new ResourceManagementClient(new Microsoft.Rest.TokenCredentials(_token.AccessToken));
            _sqlMgmtClient = new SqlManagementClient(new TokenCloudCredentials(_subscriptionId, _token.AccessToken));
            DatabaseCreateOrUpdateResponse dbr = CreateOrUpdateDatabase(_sqlMgmtClient, _resourceGroupName, _serverName, _databaseName, _databaseEdition, _databasePerfLevel);
            Console.WriteLine("Database: " + dbr.Database.Id);
        }
        private static AuthenticationResult GetToken(string tenantId, string applicationId, string applicationSecret)
        {
            AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/" + tenantId);
            _token = authContext.AcquireToken("https://management.core.windows.net/", new ClientCredential(applicationId, applicationSecret));
            return _token;
        }
        static DatabaseCreateOrUpdateResponse CreateOrUpdateDatabase(SqlManagementClient sqlMgmtClient, string resourceGroupName, string serverName, string databaseName, string databaseEdition, string databasePerfLevel)
        {
            // Retrieve the server that will host this database
            Server currentServer = sqlMgmtClient.Servers.Get(resourceGroupName, serverName).Server;

            // Create a database: configure create or update parameters and properties explicitly
            DatabaseCreateOrUpdateParameters newDatabaseParameters = new DatabaseCreateOrUpdateParameters()
            {
                Location = currentServer.Location,
                Properties = new DatabaseCreateOrUpdateProperties
                {
                    CreateMode = DatabaseCreateMode.PointInTimeRestore,
                    Edition = databaseEdition,
                    SourceDatabaseId = "/subscriptions/subscriptionId/resourceGroups/tomnewgroup/providers/Microsoft.Sql/servers/tomsunsqltest/databases/sourceDatabaseName",
                    RestorePointInTime  = DateTime.Parse("2017-02-09T02:28:20.21Z"),//Restore Point time
                    RequestedServiceObjectiveName = databasePerfLevel
                }
            };

            DatabaseCreateOrUpdateResponse dbResponse = sqlMgmtClient.Databases.CreateOrUpdate(resourceGroupName, serverName, databaseName, newDatabaseParameters);
            return dbResponse;
        }

packages.config file:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Hyak.Common" version="1.0.2" targetFramework="net462" />
  <package id="Microsoft.Azure.Common" version="2.1.0" targetFramework="net462" />
  <package id="Microsoft.Azure.Common.Authentication" version="1.7.0-preview" targetFramework="net462" />
  <package id="Microsoft.Azure.Common.Dependencies" version="1.0.0" targetFramework="net462" />
  <package id="Microsoft.Azure.Management.ResourceManager" version="1.4.0-preview" targetFramework="net462" />
  <package id="Microsoft.Azure.Management.Sql" version="0.51.0-prerelease" targetFramework="net462" />
  <package id="Microsoft.Bcl" version="1.1.9" targetFramework="net462" />
  <package id="Microsoft.Bcl.Async" version="1.0.168" targetFramework="net462" />
  <package id="Microsoft.Bcl.Build" version="1.0.14" targetFramework="net462" />
  <package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="2.18.206251556" targetFramework="net462" />
  <package id="Microsoft.Net.Http" version="2.2.22" targetFramework="net462" />
  <package id="Microsoft.Rest.ClientRuntime" version="2.1.0" targetFramework="net462" />
  <package id="Microsoft.Rest.ClientRuntime.Azure" version="3.1.0" targetFramework="net462" />
  <package id="Microsoft.Rest.ClientRuntime.Azure.Authentication" version="2.0.1-preview" targetFramework="net462" />
  <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net462" />
</packages>

请打开一个支持案例,以便我们更好地了解问题

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM