VS2019 Azure Service Authentication Account Selection for local debugging - azure

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.

Related

Microsoft Graph permissions issue when using managed identity and DefaultAzureCredential

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)

Connect to Azure SQL Database using Managed Identity

I am trying to configure connecting to azure sql using managed identity. However before, I need to connect to sql azure from visual studio using AD identity.
I have followed steps here.
https://learn.microsoft.com/en-us/azure/app-service/tutorial-connect-msi-sql-database?tabs=windowsclient%2Cef%2Cdotnet#3-modify-your-project
I have this code in console app.
SqlConnectionStringBuilder builder = new
Microsoft.Data.SqlClient.SqlConnectionStringBuilder();
builder.DataSource = "sqlserveraddress";
builder.InitialCatalog = "dbaddress";
string connstring = builder.ConnectionString;
await using var conn = new Microsoft.Data.SqlClient.SqlConnection(connstring)
{
AccessToken = await GetAzureSqlAccessToken()
} ;
await conn.OpenAsync();
As required, I have added my visual studio App service authentication identity user in sql azure db.
CREATE USER "user#domain.com" FROM EXTERNAL
PROVIDER;
ALTER ROLE db_datareader ADD MEMBER
"user#domain.com";
ALTER ROLE db_datawriter ADD MEMBER
"user#domain.com";
ALTER ROLE db_ddladmin ADD MEMBER
"user#domain.com";
GO
Now if i try running my console application, I get following error.
If i try to decode the access token it shows the user I have added to sql azure. user#domain.com.
What Am I Missing here??
You need to set the created Managed Identity as admin in SQL Server.
Follow this: Azure SQL Server -> Settings -> Azure Active Directory
Now click on Set Admin option and search for the Managed Identity to which you want to give access.
Click on Save.

Azure Service Bus managed identity in Visual Studio returning 401 - Token issuer is invalid

I'm attempting to access Azure Service Bus using a managed identity from my code. At the moment I'm just trying this locally.
When I debug my code I get the following error
System.UnauthorizedAccessException: Put token failed. status-code: 401, status-description: InvalidIssuer: Token issuer is invalid
Here is my service bus instance
Here is my user with Azure Service Bus Data Owner permissions
And here is my code
_client = new ServiceBusClient("oconnorevents.servicebus.windows.net", new DefaultAzureCredential());
I am logged into Visual Studio as the same user added to the service bus. I also tried logging in via the CLI but it didn't help.
Where am I going wrong here?
I've looked at this similar recent question here but the solutions proposed didn't work for me.
Since I have access to several different tenants, Visual Studio sometimes gets confused. Another way you can handle this is to continue to use the DefaultAzureCredential, but to give Visual Studio a hint about which tenant to use.
First left click the your project and examine the properties and then:
Left-click "Debug"
Left-click the "Add" button to add an environment variable
For name use "AZURE_TENANT_ID" and for value use your tenant id. Yes, that is a bogus tenant id in the picture :-)
Reference
https://learn.microsoft.com/en-us/dotnet/api/azure.identity.environmentcredential?view=azure-dotnet
https://damienbod.com/2020/10/09/using-key-vault-certificates-with-microsoft-identity-web-and-asp-net-core-applications/
If you use DefaultAzureCredential to auth, it will try several credential types to auth as mentioned here, one of them is VisualStudioCredential, but it will auth to the home AAD tenant of the user logged in VS, in your case, I suppose the service bus is in a subscription which is not under the home tenant of the user.
I can also reproduce your issue on my side.
To solve the issue, just use VisualStudioCredential directly, then simply specify the TenantId via VisualStudioCredentialOptions, then it will work fine.
Sample:
To find the TenantId, just navigate to the Azure Active Directory which the subscription of your service bus located.
TokenCredential tokenCredential = new VisualStudioCredential(new VisualStudioCredentialOptions {TenantId = "xxxxxxx" });
ServiceBusClient client = new ServiceBusClient("xxx.servicebus.windows.net", tokenCredential);
Specify the exact tenant id by adding the following key to local.settings.json.
"AZURE_TENANT_ID": "your tenant id"
I tried to create an azure function that receives messages from a service bus queue using a managed identity trigger and it worked for me.
late to the party but I got it working on my local Visual Studio with this code
var tokenCredential = new VisualStudioCredential(new VisualStudioCredentialOptions { TenantId = "xxx-xxx" });
ServiceBusClient client = new ServiceBusClient("my-name-space.servicebus.windows.net", tokenCredential);
sender = client.CreateSender('my-topic');
var msgBody = new Person{ Name = 'joe'};
await sender.SendMessageAsync(new ServiceBusMessage(JsonConvert.SerializeObject(msgBody)));
Also, remember to sign in to Azure in your Visual Studio,
and assign your account to the role "Azure Service bus Data Sender" , see below:

.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);

Access Azure KeyVault from Xamarin Form

I need to get a secret from the keyVault (functionKey) so that I can access my functions.
I use the below code that works
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient =
new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var secret = await keyVaultClient.GetSecretAsync("mysecretIdentifier").ConfigureAwait(false);
var key = secret.Value;
but the above requires in Visual Studio 2019 tool-options- Azure service Authentication I have to choose an account
How does it work once the app is deployed?
How does it know which subscription to use?
Just trying to figure out how it will authenticate the azure keyvault?
Any ideas?
thanks
I think your mobile application should never have to query directly the keyvault. Because if you do so your secrets could be retrieved (your secrets will be present in the memory of your mobile application). Check this post about that.
I don't know what you are trying to do but best is to use Azure Functions Easy Auth. Basically it is you will request a token for your identified user on your xamarin application and use this token to query the Azure Function.

Resources