Microsoft Graph permissions issue when using managed identity and DefaultAzureCredential - azure

I have set up a test project that follows this microsoft guide: https://learn.microsoft.com/en-us/azure/app-service/scenario-secure-app-access-microsoft-graph-as-app?tabs=azure-powershell
The only difference that I made from that tutorial is the code portion. I changed it to look like this:
TokenCredential tokenCredential = new DefaultAzureCredential();
var scopes = new[] { "https://graph.microsoft.com/.default" };
var graphClient = new GraphServiceClient(tokenCredential, scopes);
var group = graphClient.Groups["<my-group-id>"].Request().GetAsync().Result;
Everything works as expected when I publish the website and access it, but when I run this code locally I receive
Insufficient privileges to complete the operation.
I am signed into VS using the same account that I am using in Azure portal (it's a global admin account). Is there any other configuration setting that I am missing so that I can run this code and test locally?

Usually you need one of the following permissions to query groups i.e delegated and application permissions : GroupMember.Read.All, Group.Read.All, Directory.Read.All, Group.ReadWrite.All, Directory.ReadWrite.All User.Read.All
Run VS as administrator and also give user administrator role.
But visual studio may not work in this case . So please try with
different credential type like client secret/certificate credential
with your app .
In local debugging ,use Shared Token Cache Credential ,as in
your local environment, DefaultAzureCredential uses the shared token
credential from the IDE.
In Visual Studio, you can set the account that you want to use when
debugging using VS : under Options -> Azure Service Authentication.
Please check Azure Managed Service Identity And Local Development by Rahul Nath (rahulpnath.com)
If multiple accounts are configured, try to set the SharedTokenCacheUsername property to that specific account to use.
var azureCredentialOptions = new DefaultAzureCredentialOptions();
azureCredentialOptions.SharedTokenCacheUsername = "<azure ad User Name>";
var credential = new DefaultAzureCredential(azureCredentialOptions);
Reference: DefaultAzureCredential: Unifying How We Get Azure AD Token | Rahul Nath (rahulpnath.com)

Related

How to ask DefaultAzureCredential to use my user credential locally

I'm trying to develop a web app on an Azure VM that uses Azure Key Vault. Later this app will also be deployed to Azure. As far as I know, the most straight forward way to make the app work, both locally and deployed, with the key vault, is to use the DefaultAzureCredential class. The code would be like this:
string kvUri = "https://" + keyvaultName + ".vault.azure.net";
SecretClient client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
KeyVaultSecret secret = await client.GetSecretAsync(secretName);
At runtime, the provider will try different credential types in order.
This sounds exactly what I want:
When developing locally (on the Azure VM, though), I want to use my user credential (user identity added to the key vault's permission) without any configuration, since I have already logged into the Visual Studio using the same user credential.
Once deployed to Azure, I want to use the app registration credential (also added to the key vault's permission).
But when running the app locally, I'm getting a 403 error The user, group or application .... does not have secrets get permission on key vault ...
After looking up the object id in the error message, I realize it's the dev machine Azure VM's credential that the application uses, not my user credential.
Is there a way to change this behavior?
To prevent the Azure VM from getting a token, you can exclude the ManagedIdentityCredential in your Development environment and only enable it in a Non-Development environment.
if (environment.IsDevelopment())
{
var credentials = new DefaultAzureCredential(new DefaultAzureCredentialOptions
{
ExcludeManagedIdentityCredential = true,
ExcludeAzureCliCredential = true
});
}
else
{
var credentials = new DefaultAzureCredential(new DefaultAzureCredentialOptions
{
ExcludeVisualStudioCodeCredential = true,
ExcludeVisualStudioCredential = true
});
}
Once deployed to Azure, I want to use the app registration credential (also added to the key vault's permission).
An Azure App Service can use a managed identity as well. There is no need for a separate App Registration.
See https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme#key-concepts for more information.
Create and identity if you wish to use (default identity)
appservice -> select you application -> identity->enable it ->should give you a Id
and than add it to key Vault Access policy
alternatively app registration can be used with tenantId,clientId,secret to connect to keyvault

.net core key vault link fails with Access Forbidden on local environment

I am running the following functionality as a part of Main method of my .net core web application
private static void LinkKeyVault(IConfigurationBuilder config, string keyVaultEndpoint)
{
if (!string.IsNullOrEmpty(keyVaultEndpoint))
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
config.AddAzureKeyVault(keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
}
}
When I am running this code on my local dev machine I am getting the following error "Operation returned an invalid status code 'Forbidden'". When this code runs in Azure under app service user assigned managed identity everything works just fine. On my local environment I am logged in with my Azure AD user which was granted access permissions using key vault access policy, the permissions are the same as for user assigned managed identity.
dfrds-dev-web-identity is the user assigned managed identity, DFRDDevelopers is a group that my Azure AD account is a part of.
It should work, please make sure the group in which the user account located is a Security group, not a Microsoft 365 group, just the Security group is supported in this feature.
Reference - https://learn.microsoft.com/en-us/azure/key-vault/general/secure-your-key-vault#data-plane-and-access-policies
To grant data plane access to several users, create an Azure AD security group and add users to that group.
Also, if you want to use Visual Studio to auth, make sure you logged in with the correct account, and try to use RunAs=Developer; DeveloperTool=VisualStudio in the code to make sure it uses the Visual Studio to auth.
var azureServiceTokenProvider = new AzureServiceTokenProvider(RunAs=Developer; DeveloperTool=VisualStudio);

Retrieve Azure KeyVault secret using client secret

I'm experimenting with various Azure features and currently want to retrieve a secret from KeyVault.
Straight to the case:
I'm using this nuget package to interact with my azure resources.
I've developed a simple .NET Core console app and run it locally.
I have a KeyVault resource with one secret defined which is active and not expired.
I've registered an App in AAD so my locally shipped .NET Core console app has an identity within AAD.
Than I've created a "client secret" within this registered app in AAD to use it to authenticate myself as an app.
After that I've added access policy in my KeyVault resource to allow GET operation for secrets for this registered app:
Then I've developed a small piece of code which should retrieve the desired secret:
public class AzureAuthentication
{
public async Task<string> GetAdminPasswordFromKeyVault()
{
const string clientId = "--my-client-id--";
const string tenantId = "--my-tenant-id--";
const string clientSecret = "--my-client-secret--";
var credentials = new ClientSecretCredential(tenantId, clientId, clientSecret);
var client = new SecretClient(new Uri("https://mykeyvaultresource.vault.azure.net"), credentials);
var secret = await client.GetSecretAsync("admincreds");
return secret.Value.Value;
}
}
However when I'm trying to do this I'm getting an AccessDenied error:
Am I missing something painfully obvious here? Or there is some latency (>30 min for this moment) for which changes from Access policies screen in KeyVault resource are applied?
I test your code and Get permission, it works fine.
From your screenshot, it looks you didn't add the correct service principal related to the AD App to the Access policies.
If you add the service principal related to the AD App, it will appear as APPLICATION, not COMPOUND IDENTITY.
So when you add it, you could search for the client Id(i.e. application Id) or the name of your App Registration directly, make sure you add the correct one.
Make sure your AD App(service principal) has the correct permission in your keyvault -> Access policies

How can I allow a service account to access my REST API when using Roles-based Authorization in Azure?

Summary: I have a REST API that I use for functional testing. I only allow people or groups in a specific "Tester" role to hit the API. I want to trigger this functional testing during an Azure DevOps Release Pipeline automatically, but I can't figure out how to authorize the machine account to hit the API.
Details:
I have this API secured with [Authorize(Roles = "Tester")]
[Route("quotas/developers")]
[HttpGet]
[Authorize(Roles = "Tester")]
[SwaggerResponse(HttpStatusCode.OK, "Successful operation", Type = typeof(DeveloperQuota[]))]
public async Task<List<DeveloperQuota>> GetDeveloperQuota([FromUri]string developerUpn)
To set this up, I have an Enterprise Application registered in Azure Active Directory. In the manifest, I declare the role.
And then in the Enterprise Application I add some users and groups which are assigned the role "Tester."
This works fine for running my functional tests by hand. I run the tests, it pops up an oauth dialog for me to enter my credentials, it grabs my Bearer token from the successful auth request then passes it along to the APIs.
private string GetActiveDirectoryToken()
{
string authority = this.configuration.ActiveDirectoryAuthority;
string resource = this.configuration.ActiveDirectoryAudience;
string keyVaultUri = this.configuration.KeyVaultUri;
IKeyVaultAdapterFactory keyVaultAdapterFactory = new KeyVaultAdapterFactory();
var keyVaultAdapter = keyVaultAdapterFactory.CreateInstance(KeyVaultServicePrincipal.PowerShellAppId);
SecureString clientIdSecure = keyVaultAdapter.GetAzureKeyVaultSecretSecure(keyVaultUri, "GasCallbackRegistrationClientID", null).Result;
SecureString redirectUriSecure = keyVaultAdapter.GetAzureKeyVaultSecretSecure(keyVaultUri, "GasCallbackRegistrationClientIDRedirectUri", null).Result;
var authContext = new AuthenticationContext(authority);
var result = authContext.AcquireTokenAsync(
resource,
SecureStringUtilities.DecryptSecureString(clientIdSecure),
new Uri(SecureStringUtilities.DecryptSecureString(redirectUriSecure)),
new PlatformParameters(PromptBehavior.Auto)).Result;
return result.AccessToken;
}
Of course, if I'm running this during automation, there will be nothing to fill in the dialog with creds, nor do I want to be storing a copy of these creds, especially since these creds roll on a schedule which are maintained elsewhere.
My thought was that I could create an Azure Service Principal, associate a cert with the service principal, install the cert on my deployment machine, login as the Service Principal if the cert was available, and then put that Service Principal in the "Tester" role. The problem is I can't add a Service Principal as a user in the Enterprise Application. It only appears to allow me to add "Users and groups." I similarly can't add a service principal to a group.
Any thoughts on how I can authorize my deployment box to hit these APIs?
Roles published for applications are treated as application permissions and not assignable to other apps via the "Users and Groups" assignment screen.
To assign the app permissions to a client app, go to the client app's registration page, click on Api Permissions and then Add a Permission. Select the My Api tab, search for your application that published the app roles and you'd see the app role listed in the list below. Select that, save and then grant admin consent.

VS2019 Azure Service Authentication Account Selection for local debugging

Using VS2019, I have specified a temporary "developer account", using Tools/Options/Azure Service Authentication/Account Selection, for my app to "authenticate and access Azure resources with when debugging from Visual Studio". The developer account has access to an Azure SQL database. When I debug, my app gets a token as follows:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder["Data Source"] = serverName;
builder["Initial Catalog"] = dbName;
builder["Persist Security Info"] = "False";
builder["MultipleActiveResultSets"] = "False";
builder["Encrypt"] = "True";
builder["TrustServerCertificate"] = "False";
builder["Connect Timeout"] = 15;
var cancellationToken = new CancellationToken();
var conn = new SqlConnection(builder.ConnectionString);
conn.AccessToken = new AzureServiceTokenProvider().GetAccessTokenAsync("https://database.windows.net/").GetAwaiter().GetResult();
return conn.AccessToken;
However, when I examine the token returned it is NOT the token for the developer account identity I specified, it is for my normal identity I use to run Visual Studio. A co-worker has been able to do this in VS2019 with a developer account that's in the same Azure AD groups as my developer account. But for some local environment reason this is not working for me. Note that in SQL Server Management Studio I can access the SQL Azure database using my developer account with no problem at all.
Has anyone else had this debugging identity problem and been able to solve it? Thanks in advance for any light you can shed on this.
Sounds like you need to add the developer account to your Azure Service Authentication
On the drop down add the Dev account you are trying to use and make sure you make it your default account for Azure.

Resources