Azure AD B2C Audit Logs - Graph API - azure

I am trying to retrieve the Azure AD B2C users sign-in audit logs, but its throw below error
var signIns = await _graphClient.AuditLogs.SignIns
.Request()
.GetAsync();
fail:
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request.
Status Code: Forbidden
Microsoft.Graph.ServiceException: Code: Authentication_RequestFromNonPremiumTenantOrB2CTenant
Message: Neither tenant is B2C or tenant doesn't have premium license
Inner error:
AdditionalData:
date: 2020-10-05T10:12:34
request-id: 1740dcc7-3ffd-4d81-a721-a18e3fee0e1a
client-request-id: 1740dcc7-3ffd-4d81-a721-a18e3fee0e1a
ClientRequestId: 1740dcc7-3ffd-4d81-a721-a18e3fee0e1a
at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
at Microsoft.Graph.BaseRequest.SendRequestAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
at Microsoft.Graph.BaseRequest.SendAsync[T](Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
at Microsoft.Graph.AuditLogRootSignInsCollectionRequest.GetAsync(CancellationToken cancellationToken).
Thanks in advance

This is accessing sign-in reports requires an Azure Active Directory premium 1 (P1) license.
Check it in Azure Portal Licenses.

Related

Teams Bot Authentication with managed identity is failing with error : Failed to acquire token for client credentials

I have implemented Teams bot and authenticating it using managed identity.But getting below error:
Tried to get token using Managed Service Identity. Access token could not be acquired. Received a non-retryable error. MSI ResponseCode: BadRequest, Response: {"error":"invalid_request","error_description":"Identity not found"}
at Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.GetAuthResultAsyncImpl(String resource, String authority, Boolean forceRefresh, CancellationToken cancellationToken)
at Microsoft.Bot.Connector.Authentication.ManagedIdentityAuthenticator.AcquireTokenAsync(Boolean forceRefresh)
at Microsoft.Bot.Connector.Authentication.Retry.Run[TResult](Func`1 task, Func`3 retryExceptionHandler)
I have created bot managed identity and using that identity while creating azure bot.I have bot code deployed on AKS(kubernetes) cluster.And added owner role to the managed identity of bot in AKS.
Based on documentation, connector service will take care of generating token based on values provided in appsettings.deve.json
What is the possible issue here?

Login failed for user ''. while trying to access database using User Assigned ManagedIdentity [duplicate]

I am trying to use a User Assigned Managed Identity in one of our applications. I also read about the differences between System Assigned Managed Identity and User Assigned Managed Identity.
It is very clear to me that a System Assigned Managed Identity cannot be used locally as there you're assigning an identity to an Azure Resource.
However I am not clear if a User Assigned Managed Identity can be used locally. Only thing I could find is the following:
In my scenario, I would like to read some secrets from an Azure Key Vault. I have created a User Assigned Managed Identity and configured access policies on the Key Vault to give necessary permissions to this identity. Considering I am using this identity to access Azure Key Vault (which is an Azure resource), my expectation is that it should work regardless of the location (using JetBrains Rider as my IDE) from where my code is running.
However when I try to do something like:
var managedIdentityCredential = new ManagedIdentityCredential("managed-identity-id");
SecretClient secretClient = new(new Uri("https://mykeyvault.vault.azure.net/"), managedIdentityCredential);
KeyVaultSecret secret = await secretClient.GetSecretAsync(key);
I get the Azure.Identity.CredentialUnavailableException with ManagedIdentityCredential authentication unavailable. No Managed Identity endpoint found error message when I run the code locally:
Azure.Identity.CredentialUnavailableException: ManagedIdentityCredential authentication unavailable. No Managed Identity endpoint found.
at Azure.Identity.ManagedIdentityClient.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
at Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex)
at Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
at Azure.Identity.ManagedIdentityCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.AuthenticateRequestAsync(HttpMessage message, Boolean async, AuthenticationChallenge challenge)
at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.ProcessCoreAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
at Azure.Core.Pipeline.RetryPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
at Azure.Core.Pipeline.RetryPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
at Azure.Core.Pipeline.HttpPipeline.SendRequestAsync(Request request, CancellationToken cancellationToken)
at Azure.Security.KeyVault.KeyVaultPipeline.SendRequestAsync(Request request, CancellationToken cancellationToken)
at Azure.Security.KeyVault.KeyVaultPipeline.SendRequestAsync[TResult](RequestMethod method, Func`1 resultFactory, CancellationToken cancellationToken, String[] path)
at Azure.Security.KeyVault.Certificates.CertificateClient.GetCertificateAsync(String certificateName, CancellationToken cancellationToken)
Any insights into this will be highly appreciated.
No. User managed identity is also not supported with ManagedIdentityCredential in the local environment.
You should use DefaultAzureCredential for the code to work in local environment.
See the Note tip here.
Note
The ManagedIdentityCredential works only in Azure environments of
services that support managed identity authentication. It doesn't work
in the local environment. Use DefaultAzureCredential for the code
to work in both local and Azure environments as it will fall back to a
few authentication options including managed identity.
In case you want to use a user-asigned managed identity with the
DefaultAzureCredential when deployed to Azure, specify the
clientId.

AAD-Integrated Authentication with Azure Active Directory fails

We have an ADFS setup completed on one of our Azure virtual machine, and we have one Sql managed Instance created in azure portal.
We have federated our domain and successfully connected with 'Sql managed Instance' via AAD-Integrated authentication from SSMS.
Our problem is that when we try to connect this Sql managed Instance from our IIS application with AAD-Integrated authentication method
(string ConnectionString = #"Data Source=XXXXXXXXX; Authentication=Active Directory Integrated; Initial Catalog=testdb;")
, we get the following error on screen:
Message - > One or more errors occurred. Inner Exception -> System.AggregateException: One or more errors occurred. ---> AdalException: MSIS7069: The specified request failed. at ADALNativeWrapper.ADALGetAccessToken(String username, IntPtr password, String stsURL, String servicePrincipalName, ValueType correlationId, String clientId, Boolean* fWindowsIntegrated, Int64& fileTime) at System.Data.SqlClient.ActiveDirectoryNativeAuthenticationProvider.<>c__DisplayClass2_0.b__0() at System.Threading.Tasks.Task`1.InnerInvoke() at System.Threading.Tasks.Task.Execute() --- End of inner exception stack trace --- at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) at System.Data.SqlClient.SqlInternalConnectionTds.<>c__DisplayClass134_1.b__0() at System.Threading.Tasks.Task`1.InnerInvoke() at System.Threading.Tasks.Task.Execute() ---> (Inner Exception #0) AdalException: MSIS7069: The specified request failed. at ADALNativeWrapper.ADALGetAccessToken(String username, IntPtr password, String stsURL, String servicePrincipalName, ValueType correlationId, String clientId, Boolean* fWindowsIntegrated, Int64& fileTime) at System.Data.SqlClient.ActiveDirectoryNativeAuthenticationProvider.<>c__DisplayClass2_0.b__0() at System.Threading.Tasks.Task`1.InnerInvoke() at System.Threading.Tasks.Task.Execute()<---
Also we checked into ADFS logged issues and got the following error logged as follows:
Log Name: AD FS/Admin
Source: AD FS
Date: 7/29/2021 12:26:45 PM
Event ID: 111
Task Category: None
Level: Error
Keywords: AD FS
User: Domain\testuser
Computer: Name of our adfs server(Not mentioned the exact name due to sensitive data)
Description:
The Federation Service encountered an error while processing the WS-Trust request.
Request type: http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue
Additional Data
Exception details:
Microsoft.IdentityServer.Service.SecurityTokenService.ADAccountValidationException: MSIS3173: Active Directory account validation failed. ---> Microsoft.IdentityServer.ClaimsPolicy.Engine.AttributeStore.Ldap.AttributeStoreDSGetDCFailedException: Exception of type 'Microsoft.IdentityServer.ClaimsPolicy.Engine.AttributeStore.Ldap.AttributeStoreDSGetDCFailedException' was thrown.
Are we missing anything in the whole process?
Edit1:
I have one confusion regarding federated domain. The domain which we are using in our client machine, has to be primary domain in our Azure active directory OR can it be just in custom domain list in Azure active directory?
Edit2:
Finally, we were successful in connecting to our IIS application via AAD-Integrated authentication. We just changed our application pool's identity from ApplicationPoolIdentity(default option) to our domain user and voila, it worked like a charm. Hope somebody can get benefited from this.

Can a "User Assigned Managed Identity" be used locally?

I am trying to use a User Assigned Managed Identity in one of our applications. I also read about the differences between System Assigned Managed Identity and User Assigned Managed Identity.
It is very clear to me that a System Assigned Managed Identity cannot be used locally as there you're assigning an identity to an Azure Resource.
However I am not clear if a User Assigned Managed Identity can be used locally. Only thing I could find is the following:
In my scenario, I would like to read some secrets from an Azure Key Vault. I have created a User Assigned Managed Identity and configured access policies on the Key Vault to give necessary permissions to this identity. Considering I am using this identity to access Azure Key Vault (which is an Azure resource), my expectation is that it should work regardless of the location (using JetBrains Rider as my IDE) from where my code is running.
However when I try to do something like:
var managedIdentityCredential = new ManagedIdentityCredential("managed-identity-id");
SecretClient secretClient = new(new Uri("https://mykeyvault.vault.azure.net/"), managedIdentityCredential);
KeyVaultSecret secret = await secretClient.GetSecretAsync(key);
I get the Azure.Identity.CredentialUnavailableException with ManagedIdentityCredential authentication unavailable. No Managed Identity endpoint found error message when I run the code locally:
Azure.Identity.CredentialUnavailableException: ManagedIdentityCredential authentication unavailable. No Managed Identity endpoint found.
at Azure.Identity.ManagedIdentityClient.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
at Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex)
at Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
at Azure.Identity.ManagedIdentityCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.AuthenticateRequestAsync(HttpMessage message, Boolean async, AuthenticationChallenge challenge)
at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.ProcessCoreAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
at Azure.Core.Pipeline.RetryPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
at Azure.Core.Pipeline.RetryPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
at Azure.Core.Pipeline.HttpPipeline.SendRequestAsync(Request request, CancellationToken cancellationToken)
at Azure.Security.KeyVault.KeyVaultPipeline.SendRequestAsync(Request request, CancellationToken cancellationToken)
at Azure.Security.KeyVault.KeyVaultPipeline.SendRequestAsync[TResult](RequestMethod method, Func`1 resultFactory, CancellationToken cancellationToken, String[] path)
at Azure.Security.KeyVault.Certificates.CertificateClient.GetCertificateAsync(String certificateName, CancellationToken cancellationToken)
Any insights into this will be highly appreciated.
No. User managed identity is also not supported with ManagedIdentityCredential in the local environment.
You should use DefaultAzureCredential for the code to work in local environment.
See the Note tip here.
Note
The ManagedIdentityCredential works only in Azure environments of
services that support managed identity authentication. It doesn't work
in the local environment. Use DefaultAzureCredential for the code
to work in both local and Azure environments as it will fall back to a
few authentication options including managed identity.
In case you want to use a user-asigned managed identity with the
DefaultAzureCredential when deployed to Azure, specify the
clientId.

Does Azure App Service running Asp.Net Core 3.1 in a Linux docker container support User Assigned Managed Identity?

I have an Asp.Net Core 3.1 application that reads its configuration from a Key Vault using the following code:
var keyVaultEndpoint = builtConfig["ProductKeyVaultUri"];
if (!string.IsNullOrEmpty(keyVaultEndpoint))
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));
config.AddAzureKeyVault(keyVaultEndpoint, keyVaultClient,
new DefaultKeyVaultSecretManager());
}
It uses the most recent version of the Microsoft.Azure.Services.AppAuthentication package to date - 1.4.0
The application is deployed to an Azure App Service with a System Managed Identity (MI for short), which can read secrets from the relevant Key Vault. It works.
Indeed when I remove the System MI from the Key Vault access policy and restart the App Service, I get this:
Unhandled exception. Microsoft.Azure.KeyVault.Models.KeyVaultErrorException: Access denied. Caller was not found on any access policy.
Caller: appid=6f215b10-33a1-4e5d-b3b7-20e8f3d3b587;oid=3d6af26c-af56-4cef-a832-41c2303a8cbe;numgroups=0;iss=https://sts.windows.net/2...b/
Vault: a...v;location=eastus2
at Microsoft.Azure.KeyVault.KeyVaultClient.GetSecretsWithHttpMessagesAsync(String vaultBaseUrl, Nullable`1 maxresults, Dictionary`2 customHeaders, CancellationToken cancellationToken)
at Microsoft.Azure.KeyVault.KeyVaultClientExtensions.GetSecretsAsync(IKeyVaultClient operations, String vaultBaseUrl, Nullable`1 maxresults, CancellationToken cancellationToken)
at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.LoadAsync()
at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.Load()
at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
at Microsoft.Extensions.Hosting.HostBuilder.BuildAppConfiguration()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at Gateway.Program.Main(String[] args)
/opt/startup/init_container.sh: line 20: 10 Aborted (core dumped) dotnet Gateway.dll
(I scrubbed the tenantId and the key vault name)
It gives us the AppId (6f215b10-33a1-4e5d-b3b7-20e8f3d3b587) and the ObjectId (3d6af26c-af56-4cef-a832-41c2303a8cbe) which indeed match the System MI.
So far so good.
Now, I replace the System MI with a User Assigned MI, which has the access to the secrets in the same KV. However, restarting the App Service does not yield any good. The web app fails to read the secrets from the Key Vault which aborts the start of the container. Here is what docker logs tell me:
Unhandled exception. Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException: Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/2...b. Exception Message: Tried the following 3 methods to get an access token, but none of them worked.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/2...b. Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. Received a non-retryable error. MSI ResponseCode: BadRequest, Response: {"statusCode":400,"message":"Unable to load requested managed identity.","correlationId":"1b0ee635-0805-4438-8ae8-747e9f6dd7c2"}
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/2...b. Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. Environment variable LOCALAPPDATA not set.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/2...b. Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. /bin/bash: az: No such file or directory
at Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.GetAuthResultAsyncImpl(String resource, String authority, CancellationToken cancellationToken)
at Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.<get_KeyVaultTokenCallback>b__8_0(String authority, String resource, String scope)
at Microsoft.Azure.KeyVault.KeyVaultCredential.PostAuthenticate(HttpResponseMessage response)
at Microsoft.Azure.KeyVault.KeyVaultCredential.ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Azure.KeyVault.KeyVaultClient.GetSecretsWithHttpMessagesAsync(String vaultBaseUrl, Nullable`1 maxresults, Dictionary`2 customHeaders, CancellationToken cancellationToken)
at Microsoft.Azure.KeyVault.KeyVaultClientExtensions.GetSecretsAsync(IKeyVaultClient operations, String vaultBaseUrl, Nullable`1 maxresults, CancellationToken cancellationToken)
at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.LoadAsync()
at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.Load()
at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
at Microsoft.Extensions.Hosting.HostBuilder.BuildAppConfiguration()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at Gateway.Program.Main(String[] args)
/opt/startup/init_container.sh: line 20: 10 Aborted (core dumped) dotnet Gateway.dll
From which I conclude that the docker must be told explicitly the name of the User Assigned MI. It kind of makes sense, because an App Service may have many User Assigned MIs, but only one System MI.
So, the question is - can we use User Assigned MI at all in this scenario?
The issue might be that you are not telling AzureServiceTokenProvider the id of the user-assigned MI.
Here in the docs you can see samples of the connection string syntax: https://learn.microsoft.com/en-us/azure/key-vault/service-to-service-authentication#connection-string-support.
For your case, specify a connection string like:
RunAs=App;AppId={ClientId of user-assigned identity}
And use that as a constructor argument for the token provider.
By default the provider tries only system-assigned MI.

Resources