Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Microsoft.Azure.Management.ApiManagement - Create authorization token programatically #4727

Closed
vetrivelmp opened this issue Aug 31, 2018 · 8 comments
Assignees
Labels
API Management customer-reported Issues that are reported by GitHub users external to the Azure organization. Mgmt This issue is related to a management-plane library. needs-author-feedback More information is needed from author to address the issue. question The issue doesn't require a change to the product in order to be resolved. Most issues start as that

Comments

@vetrivelmp
Copy link

Hello All,

I am trying to implement Azure API Management APIs using Microsoft.Azure.Management.ApiManagement 4.0.4-preview.

No where I see documentation for implementation. I tried below code. but I am getting authentication error. i want to know how to create authorization token programatically.

Microsoft.Rest.Azure.CloudException: 'Authentication failed. The 'Authorization' header is provided in an invalid format.'

BasicAuthenticationCredentials basicAuthenticationCredentials = new BasicAuthenticationCredentials();
basicAuthenticationCredentials.UserName = "***";
basicAuthenticationCredentials.Password = "
";

var token = "Bearer **********"; // copied bear token from https://docs.microsoft.com/en-us/rest/api/apimanagement/user/get by logging proper user name and password

ApiManagementClient apiManagementClient = new ApiManagementClient(basicAuthenticationCredentials);
apiManagementClient.SubscriptionId = "*************************************";
apiManagementClient.HttpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token);
apiManagementClient.ApiManagementService.Get("resourcegroupname", "POCAPIManagementService"); // error happening from this line

var user = apiManagementClient.User.Get("resourcegroupname", "POCAPIManagementService", "1");

@vetrivelmp vetrivelmp changed the title Microsoft.Azure.Management.ApiManagement - Create authoriation token programatically Microsoft.Azure.Management.ApiManagement - Create authorization token programatically Aug 31, 2018
@vetrivelmp
Copy link
Author

No reply for this comment ?

@shahabhijeet
Copy link
Member

Here is one way you achieve this.
When you have to pass in the credentials to your management client constructor, new up the below class.

public class myServiceCredentials : ServiceClientCredentials
    {
        private string AuthenticationToken { get; set; }
        public override void InitializeServiceClient<T>(ServiceClient<T> client)
        {
            var authenticationContext = new AuthenticationContext("https://login.windows.net/{tenantID}");
            var credential = new ClientCredential(clientId: "xxxxx-xxxx-xx-xxxx-xxx", clientSecret: "{clientSecret}");
            var result = authenticationContext.AcquireToken(resource: "https://management.core.windows.net/", clientCredential: credential);

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

@vetrivelmp
Copy link
Author

@bsiegel bsiegel added the Service Attention This issue is responsible by Azure service team. label Sep 26, 2018
@mjconnection mjconnection added the question The issue doesn't require a change to the product in order to be resolved. Most issues start as that label Jun 19, 2019
@azure-sdk azure-sdk added the customer-reported Issues that are reported by GitHub users external to the Azure organization. label Sep 24, 2020
@ghost ghost added the needs-team-attention This issue needs attention from Azure service team or SDK team label Sep 24, 2020
@ghost
Copy link

ghost commented Oct 8, 2020

Hello,

I'm trying to use Microsoft.Azure.Management.ApiManagement 6.0.0-preview to add new Products, policies, etc and manage my Azure API management progrmatically.

I used the "myServiceCredentials" from the previous post and I got a valid token as expected, now I'm trying to add new Product through ApiManagementClient.Product.CreateOrUpdate()

I have this method:

public async Task<ProductContract> CreateAPIMroducts(myContract myData)
        {
            var serviceCredentials = new AzureApiManagementServiceCredentials(); //in this class I implement ServiceClientCredentials

            ApiManagementClient myClient = new ApiManagementClient(serviceCredentials);

            ProductContract productContract = new ProductContract("displayName");

            ProductContract result =await myClient .Product.CreateOrUpdateAsync(myData.ResourceGroupName, myData.ServiceName, myData.ProductId, productContract);
            return result;
        }

So I'm trying to create new Product into my APIM instance but I got this error: Microsoft.Rest.ValidationException: 'this.Client.SubscriptionId' cannot be null.

What I understand is to assign my subscription with the client I use but I don't know if I'm right or not and how to do it

Can you please challenge me with your ideas?

thank you! 😊

@jsquire jsquire added Mgmt This issue is related to a management-plane library. and removed Service Attention This issue is responsible by Azure service team. labels Oct 12, 2020
@ghost ghost added the needs-team-triage This issue needs the team to triage. label Oct 12, 2020
@jsquire jsquire removed the needs-team-triage This issue needs the team to triage. label Oct 12, 2020
@allenjzhang
Copy link
Member

In your latest question, you need to set the subscriptionId on the client:
myClient.SubscriptionId = "YOUR SUB ID"

For your original question, you could leverage Microsoft.Rest.ClientRuntime.Azure.Authentication.ApplicationTokenProvider for easy auth. It also has auto token refresh as well.

            var credentials = await ApplicationTokenProvider.LoginSilentAsync(
                "Domain or TenantID",
                "ClientId",
                "Client Secret");
            var client = new ComputeManagementClient(credentials);

@allenjzhang allenjzhang added needs-author-feedback More information is needed from author to address the issue. and removed needs-team-attention This issue needs attention from Azure service team or SDK team labels Jan 29, 2021
@ghost ghost added the no-recent-activity There has been no recent activity on this issue. label Feb 5, 2021
@ghost
Copy link

ghost commented Feb 5, 2021

Hi, we're sending this friendly reminder because we haven't heard back from you in 7 days. We need more information about this issue to help address it. Please be sure to give us your input. If we don't hear back from you within 14 days of this comment the issue will be automatically closed. Thank you!

@ghost ghost closed this as completed Feb 20, 2021
@LockTar
Copy link

LockTar commented Mar 2, 2021

I'm working with the Microsoft.Azure.Management.ApiManagement 6.0.0-preview package as well and this issue helped me a lot. I changed the code a bit so it is better to use with the client.

AzureApiManagementServiceCredentials

public class AzureApiManagementServiceCredentials : ServiceClientCredentials
{
    private readonly string _tenantId;
    private readonly string _clientId;
    private readonly string _clientSecret;

    public AzureApiManagementServiceCredentials(string tenantId, string clientId, string clientSecret)
    {
        _tenantId = tenantId;
        _clientId = clientId;
        _clientSecret = clientSecret;
    }

    public override void InitializeServiceClient<T>(ServiceClient<T> client)
    {
        var authenticationContext = new AuthenticationContext($"https://login.microsoftonline.com/{_tenantId}");
        var credential = new ClientCredential(clientId: _clientId, clientSecret: _clientSecret);
        var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;

        if (result == null)
        {
            throw new InvalidOperationException($"Failed to obtain the JWT token for Azure API Management Rest connection for user {_clientId}");
        }

        client.HttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
    }
}

Create the ApiManagementClient:

private ApiManagementClient InitializeApiManagementClientForSubscription(string subscriptionId)
{
    //_configuration (IConfiguration) is in my case injected...
    var serviceCredentials = new AzureApiManagementServiceCredentials(
                    _configuration["TenantId"], 
                    _configuration["ClientId"], 
                    _configuration["ClientSecret"]);

    var client = new ApiManagementClient(serviceCredentials);
    client.SubscriptionId = subscriptionId;

    return client;
}

@ghost ghost removed the no-recent-activity There has been no recent activity on this issue. label Mar 2, 2021
@madshaun1984
Copy link

For your original question, you could leverage Microsoft.Rest.ClientRuntime.Azure.Authentication.ApplicationTokenProvider for easy auth. It also has auto token refresh as well.

            var credentials = await ApplicationTokenProvider.LoginSilentAsync(
                "Domain or TenantID",
                "ClientId",
                "Client Secret");
            var client = new ComputeManagementClient(credentials);

This doesn't work for creating an ApiManagementClient or is missing information. Tested with 6.0.0-preview.

@github-actions github-actions bot locked and limited conversation to collaborators Mar 29, 2023
This issue was closed.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
API Management customer-reported Issues that are reported by GitHub users external to the Azure organization. Mgmt This issue is related to a management-plane library. needs-author-feedback More information is needed from author to address the issue. question The issue doesn't require a change to the product in order to be resolved. Most issues start as that
Projects
None yet
Development

No branches or pull requests

9 participants