How to login on Azure Portal using REST APIs - azure

I plan to implement a C# app that will create Azure resources using REST APIs (API calls to Azure Resource Manager). When calling a REST API you have to authenticate by passing an authentication header "Authorization: Bearer yJ0eXAiOiJKV...".
How do I get this Bearer token? Looking online all that I found is having a Web App , you use its application_id. However i don't have any application and I don't want to create one.
I can replicate the calls that I intercept with Fiddler but I think that that is not the "recommended" way.
Have anyone faced this problem and has a solution?

Short answer: If you're developing a C# application that is going to use Azure REST APIs, then in order to get the bearer token for authentication you do need to have an Azure AD application registration (no way around that, as it's required for you to be able to authenticate using any of the supported OAuth 2.0 grant flows).
There are a few ways to make things more convenient for you though:
Use CLI to create a service principal for RBAC
From Azure Portal, open up the CLI by clicking on highlighted icon.
Now run below mentioned command
az ad sp create-for-rbac -n "MyTestSPForAzureRESTAPIs"
This does multiple things for you in a single command and provides a great way to get started with testing the REST APIs.
The created service principal is added as a "Contributor" to your Azure subscription. You can always go to Subscriptions > Your Subscription > Access control (IAM) and change that as per your requirements.
You get an application ID as well as Password/client secret that you can then use in C# code to get bearer token.
Sample output
NOTE: Since this approach gives you a client secret, you should use this only from server side applications (like a web API or Web App or Daemon service). Do NOT use client secrets from a desktop based app (like console app or WPF app) or SPA in a production scenario.
I say this because desktop based apps or SPAs are not secure enough to handle client secrets and there are other different authentication flows recommended for them. If your case happens to be any of those, look at delegated permissions from your Azure AD application where you can prompt an end user for credentials. Just comment on the answer and I can add more specific guidance around those.
Use Managed Identity in case of App Service or Azure Function
If you plan to host the C# application that you mention, using App Service or as an Azure Function, then you can make use of MSI. Even in this case an application will be created in Azure AD, but you don't need to do that or manage keys (change them regularly etc.). It's a great option, highly recommended if it suits your scenario.
Read here for more details: How to use managed identities for App Service and Azure Functions

If you just want to get the bearer token. I recommand that you could login in your account in the Azure API document. After we login then we could get the bearer token.
If we want to use code to get access token to access or modify resources, create an identity for the Azure AD application is required . This identity is known as a service principal. Then we can then assign the required permissions to the service principal.
How to registry an Azure AD application and assign role to the application, please refer to this document.
The following is demo code how to get the access token with applicationId and sercet key
public static async Task<string> GetAccessToken(string tenantId, string clientId, string clientSecretKey)
{
var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
ClientCredential clientCredential = new ClientCredential(clientId, clientSecretKey);
var tokenResponse = await context.AcquireTokenAsync("https://management.azure.com/", clientCredential);
var accessToken = tokenResponse.AccessToken;
return accessToken;
}

Related

Is it possible to call external Azure Service with AD Token from within D365/PowerApp plugins?

I am new to D365/PowerApps and wonder if i have a Azure Service, (Azure Functions or WebAPP) that is secured with Azure AD tokens (App Registrations).
Can I get an Access Token to my external services using Azure AD from within a plugin step in d365? How do I get such token on behalf of the context the plugin when running as a user.
You'll need to use Flow and compose a http request to get the token:
https://flow.microsoft.com/en-us/galleries/public/templates/edfa8fde25644f149448c8d8cff44699/call-a-web-service-from-a-powerapp/
Here's a good explanation on how to do it using the REST API:
https://stackoverflow.com/a/36982924/1384539
If I understand your question correct,
You have an Azure function APP or external azure service and that is secured by creating Azure AD App with it's roles delegation and so on.
Now you need Access token for this Azure APP with client ID and Client Secret.
We had this similar thing in Dynamics 365 i.e When we wish to use Dynamics 365 Webapi, We need to create Azure AD App and then provide roles delegation so that this app will have access to Dynamics 365.
In Plugin we can give details with client Id and Secret and then generate Token which will be used for Furthure process during plugin Execution.
Note: Most of these plugins we run under System context.
Here are few examples which will lead you to your desired direction.
Most of the Examples also talk about creating Non-Interactive user in Dynamics but in your case that shall not be needed because you are not communicating with Dynamics via (Azure AD App) rather you communicate with Azure functions or so on.
Link 1
Link 2
Link 3

Azure App Registration programmatically (Graph API)

I'm trying to register an application in Azure programmatically. Most examples are targeting use of Azure Portal, which doesn't meet my requirements. Other examples assume that I have a registered app already and hold a bearer token to use for this operation. Again that doesn't meet my requirements.
In my scenario. I'm an Azure AD administrator, and I want to programmatically register my first application, without going to the Azure Portal. Since this is easily done via portal, I was hoping to do this in code as well (http/C# preferred). And as a step 2, Add permissions and Grant admin consent - again programmatically.
Eventually, I'm using the registered app's ClientId and ClientSecret to retrieve the bearer token and then query Graph API. (This part is working fine, when I make the app registration manually via Azure Portal)
I hope this makes sense.
You can use the Microsoft Graph API.
The API to use to create an app is: https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/application_post_applications
To grant permission you can refer here

Creating an AD application using .net

I am trying to create an AD application using .net, I am able to create it with Microsoft.Azure.ActiveDirectory.GraphClient. But why I am supposed to create a native AD Application in the Azure portal prior to creation of AD Application in .net
My question is, will I be able to create a AD application without client Id of a native app?
In short no.
When you create application you need to require Delegate permission or Application permission. To assign the permission to user, you need to use app to act as an agent.
You could use the following code to get the ad token, you need to give the client id of the native app which you have granted delegate permission. You also could grant Application permission to a Web app/API which you use client id and client secret to acquire token.
var result = await authenticationContext.AcquireTokenAsync(graphResourceId, clientId, new UserPasswordCredential(userName, password));
BTW, Azure portal is an enterprise application.So, when we login and create Azure AD App, it also get the client id of azure portal.
You can simply publish your native .NET application using AAD Application Proxy. There are a number of samples that show how to do this. You need to publish your application through the application proxy and register it as a Native app.
This document details all of the steps for this: https://learn.microsoft.com/en-us/azure/active-directory/manage-apps/application-proxy-configure-native-client-application

How to add application to Azure AD using Microsoft.Azure.Management.Graph.RBAC.Fluent

I am using https://www.nuget.org/packages/Microsoft.Azure.Management.Fluent for creating resources in Azure programmatically. The package requires me to create an Azure AD Application which will be used by my console app to authenticate for the resource management api. So far so good - I created that AD app and use that in my console app, "normal" resource management is working fine.
Now I wanted to start to also programmatically create other Azure AD Applications using the https://www.nuget.org/packages/Microsoft.Azure.Management.Graph.RBAC.Fluent package, which is a direct dependency of the package mentioned above. While I can use the package e.g. for listing existing Azure AD Applications, I am getting authorization issues (401) as soon as I try to create new Azure AD applications with it. I tried playing around with the permissions I gave to the AD app used by the console app, but had no success.
Is there either a way to...
give an Azure AD Application permission to create other Azure AD Applications (this is my preferred way), and if so, which are the permissions required?
or to use the Microsoft.Azure.Management.Fluent package with an actual "human" user account that has the permissions required to create Azure AD Applications?
The https://www.nuget.org/packages/Microsoft.Azure.Management.Graph.RBAC.Fluent package uses Azure AD Graph to create the application.
And there is no such app-only permission that we can create the application. As a alternative way we can grant the Directory.AccessAsUser.All permission for the Windows Azure Active Directory and the sign-in user with Global Admin for that tenant. Here is a figure which grant the specific permission for your reference:
Update
This library which using the Resource Owner Password Credentials Grant is designed for the native client application.
In this scenario, you can register an native client app which is public app that there is no secret. Or you can perform the Resource Owner Password Credentials Grant flow using the HttpClient class. Here is a piece of code for your reference:
HttpClient client = new HttpClient();
string body = String.Format("resource={0}&client_id={1}&client_secret={2}&grant_type=password&username={3}&password={4}", Uri.EscapeDataString("https://graph.windows.net"), "{clientId}", Uri.EscapeDataString("{client_secret}"), Uri.EscapeDataString("{userName}"), Uri.EscapeDataString("{password}"));
StringContent sc = new StringContent(body,Encoding.UTF8, "application/x-www-form-urlencoded");
var resoult= client.PostAsync("https://login.microsoftonline.com/xxx.onmicrosoft.com/oauth2/token", sc).Result.Content.ReadAsStringAsync().Result;
Console.WriteLine(resoult);
In addition, since the Resource Owner Password Credentials Grant flow use the users' username/password to authentication, please ensure that the you trust the client which run this app( refer Resource Owner Password Credentials Grant).

Azure Management API access from a web app

Is it possible to gain access to the Azure Management APIs through the client ID and secret for a web app?
I have a web app through which i want to be able to manage Azure. I want to do this using the credentials of the application itself so that the current user does not have to be an azure administrator.
I have given the web app the necessary role on my subscriptions and obtained the access token through the client credentials grant flow in AD but i still get an unauthorized.
This is probably because the azure management API has no permission set other than delegated - the access works fine if i use the authorization code grant flow for the logged in user, but thats not what i want.
So to reiterate, if, given a web app that has RBAC to a subscription and is able to obtain an access token from AD, is there any way, without an interactive user, that the web app is able to use the management API??
Yes, you can obtain a token from AAD for a service principal and use that to manage resources as long as that service principal has all the access you need.
Make sure the token you get has a resource/audience of "https://management.azure.com" and is for the tenantId that the subscription is associated with.
You can also see this article from Brady Gaster that explains how to use Azure AD applications to manage Azure Services from an external app : http://www.bradygaster.com/post/using-windows-azure-active-directory-to-authenticate-the-management-libraries
EDIT : Azure AD supports Service to Service calls using OAuth 2.0 client credentials: https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx
Hope this helps,
Julien

Resources