I'm trying to add SSL to an Azure web app using a certificate retrieved from the key vault. I don't see a way to do this via the portal so I've have been trying to do it with the Azure API.
I'm able to get the certificate secret and convert it to a X509 certificate using the following code:
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
SecretBundle secret2 = await keyVaultClient.GetSecretAsync(KEY_VAULT_IDENTIFIER);
string pass = null;
X509Certificate2 certificate = new X509Certificate2(Convert.FromBase64String(secret2.Value), pass, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
I honestly don't know what to do next. I've been looking into the Microsoft.Azure.Management.Fluent library but haven't been able to get anything working.
Am I headed in the right direction? Are there any examples out there that may help?
For C# code, you can make use of Azure Management Libraries for .NET
You can use following 2 Nuget packages:
Microsoft.Azure.Management.Fluent
Microsoft.Azure.Management.ResourceManager.Fluent
Authentication
You can read the guidance here
First step will be to create a Service Principal for RBAC, give it permissions on the relevant resource group and then use the clientId, secret and tenant information in code ahead.
az ad sp create-for-rbac
Code
string clientId = "xxxxx-xxx-xxxx";
string clientSecret = "xxxxx-xxx-xxxx";
string tenant = "xxxxx-xxx-xxxx";
string subscriptionId = "xxxxx-xxx-xxxx";
var creds = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenant, AzureEnvironment.AzureGlobalCloud);
var azure = Azure.Authenticate(creds).WithSubscription(subscriptionId);
var app1 = azure.WebApps.GetByResourceGroup("rgAppService", "MyAPIServiceName");
app1.Update()
.DefineSslBinding()
.ForHostname("MyHostName")
.WithExistingCertificate("<Thumbprint of the certificate>")
.WithSniBasedSsl() // could use different method .WithIpBasedSsl in case that is relevant
.Attach()
.Apply();
Detailed Code Sample on GitHub
Managing Web Apps with custom domains in C#
This sample does a lot of things like creating the Apps, domains etc., so pick the parts that are applicable for you.
Related
Ciao,
I'm working on a Azure Function that need to read/write to a SharePoint Online list using API Graph. I've some problems on authentication.
I've followed this steps:
Created one SharePoint Online site and one list
Registered my app in Azure Active Directory (single-tenant)
Generated one secret
Added Sites.Selected authorization to my app
Requested permissions to my administrator following this link
Wrote code for use API Graph
Below app's authorizations:
Below my code:
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "my-tenant-id";
var clientId = "my-client-id";
var clientSecret = "my-secret";
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var graphServiceClient = new GraphServiceClient(clientSecretCredential, scopes);
var test = await graphServiceClient
.Sites["my-site-id"]
.Lists["my-list-id"]
.Items.Request().GetAsync();
When I execute this code I obtain this error: Message: Either scp or roles claim need to be present in the token.
How can I resolve this error?
Thank you a lot
I tried to reproduce the same in my environment and got the same error as below:
To resolve the error, I created an Azure AD Application and granted API Permissions like below:
Note that, you can only add Sites.Selected API permission based on your requirement.
I generated the token with scope as https://graph.microsoft.com/.default by using below parameters:
https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
client_id:ClientID
client_secret:ClientSecret
scope:https://graph.microsoft.com/.default
grant_type:client_credentials
Using the above generated access token, I am able to authenticate to SharePoint successfully like below:
https://graph.microsoft.com/v1.0/sites/
I am trying to access the Azure access token to get some information related to APIs hosted in Azure.
I used the code below in Visual studio and I get the token since I logged into VS with my credentials.
However, when I deployed this code I don't get the token and it throws an error, since the deployed environment does not have VS and just has the executable running there.
Sample code:
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/", "tenantId").Result;
What is the best practice to get the azure access token?
Here is the code that worked for me
var tenantId = "<Your Tenant ID>";
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var token = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com", tenantId);
var tokenCredentials = new TokenCredentials(token);
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(new AzureCredentials(
tokenCredentials,
tokenCredentials,
tenantId,
AzureEnvironment.AzureGlobalCloud))
.WithDefaultSubscription();
Note : Make sure you install Microsoft.Rest.ClientRuntime for "TokenCredentials".
REFERENCES:
Using AzureServiceTokenProvider to authenticate with the Azure Libraries for .NET
I'm working on integration with Dynamics 365 and following the Web API Sample (C#). While this works, there are two issues with the sample that I'd like to understand how to deal with.
First, the sample uses an old version of the Microsoft.IdentityModel.Clients.ActiveDirectory package, and it explains that this is because:
This sample depends on the capability to pass user credentials without a separate Azure login dialog which is not available in the 3.x version of this library.
Secondly, the sample uses this hardcoded clientId from Microsoft:
// Azure Active Directory registered app clientid for Microsoft samples
string clientId = "51f81489-12ee-4a9e-aaae-a2591f45987d";
Given that I'm using Office365 accounts and I can't see how Azure fits into the picture at all, what is the best way to achieve connectivity with Dynamics365 without the issues mentioned above?
a fast way to star with Dynamics 365 extensions with C# is using the SDK, this is available in through NuGet (XrmTooling) this way you can use a connection string with clientid and secretkey using Authorization Type ClientSecret, here is an example of the code using WhoAmIRequest. This requires using an application user, here is how to do it
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var urlMask = "RequireNewInstance=True;SkipDiscovery=True;AuthType=ClientSecret;LoginPrompt=Never;ClientSecret={0};ClientId={1};Url={2};AppId=51f81489-12ee-4a9e-aaae-a2591f45987d;RedirectUri=app://58145b91-0c36-4500-8554-080854f2ac97/";
var fullUrl = string.Format(urlMask, clientSecret, clientId, d365Url);
var conn = new CrmServiceClient(fullUrl);
var _orgService = conn.OrganizationWebProxyClient ?? (IOrganizationService)conn.OrganizationServiceProxy;
WhoAmIRequest req = new WhoAmIResquest();
WhoAmIResponse resp = _orgService.Execute(req) as WhoAmIResponse;
Console.Write(resp.UserId);
I'm a little bit lost on how you can create credentials in the Azure .NET SDK without having to call the credentials from a local file.
In my case, I have a few subscriptions and I'm storing my data in a local database. I want to make multiple calls to Azure for my VMs using the credentials I store in the database.
They have numerous classes representing ways to authenticate in the SDK Documentation, but I can't see a clear way to create access tokens or use credentials (tenant id, subscription id, client id and secret) through the SDK.
For example, when calling one of the Client classes (ComputeManagementClient) you can call it with credentials to authenticate the request to Azure but they don't seem to provide a Class to generate the credentials beyond from a file.
Does anyone have an MSDN reference?
Accoring to AzureCredentialsFactory class, we could know that we also could get the credentials FromServicePrincipal or FromUser. In your case I recomment that use the FromServicePrincipal and Microsoft.Azure.Management.Fluent to operate the Azure resource. I also do a demo for that.
Note: How to registry Azure AD Application and assign role please refer to this document.
var clientId = "clientId";
var secretKey = "secretKey";
var tenantId = "tenantId";
var subscriptionId = "subscriptionId";
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, secretKey, tenantId,AzureEnvironment.AzureGlobalCloud);
ComputeManagementClient client = new ComputeManagementClient(credentials) {SubscriptionId = subscriptionId };
var result = client.VirtualMachines.ListAllAsync().Result;
When I try to acquire a token from my Azure AD B2C app using
Microsoft.IdentityModel.Clients.ActiveDirectory - 3.13.1
Microsoft.Azure.ActiveDirectory.GraphClient - 2.1.0
like this:
var authUri = "https://login.microsoftonline.com/6b7403d6-xxxx-xxxx-xxxx-xxxxxxxxxxxx/oauth2/token";
var clientId = "59e08b82-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
var appKey = "XXXX-MyAppKey-XXXX";
var graphUri = "https://graph.windows.net/6b7403d6-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
var authenticationContext = new AuthenticationContext(authUri, false);
var clientCred = new ClientCredential(clientId, myAppKey);
var authenticationResult = await authenticationContext.AcquireTokenAsync(graphUri, clientCred);
I get
[AdalServiceException: AADSTS70001: Application '59e08b82-xxxx-xxxx-xxxx-xxxxxxxxxxxx' is not supported for this API version.
Is there a library I can use in ASP.NET MVC 5 (.NET 4.5) to get access to the B2C Active directory I created using the UI of the new Azure Portal, not PowerShell from this example?
(The xxxx's are just for privacy here)
You don't need power shell creation any more, MSFT have given permission to add a new application in Azure AD(not in azure b2c), which can be used to access Graph API in azure B2C. You need to follow below steps IN https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-graph-dotnet
Only for Deleting access for your graph api you need to do some power-shell magic...
The example you referenced: https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/
only uses powershell to set up a Service Principal.
After you have the Service Principal, you can use that in your code to access the Graph API. The example does this from a console app, but this works as well from MVC 5