AzureServiceTokenProviderException using key vault - asp.net-core

I don't know what is wrong, anyone got any ideas? I just followed this tutorial: https://learn.microsoft.com/da-dk/azure/key-vault/vs-key-vault-add-connected-service#feedback
This error only happens when the website gets published to Azure.
AzureServiceTokenProviderException: Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/1855fd54-8283-4d57-ab22-4e818e22fcf7. 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/1855fd54-8283-4d57-ab22-4e818e22fcf7. Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. An attempt was made to access a socket in a way forbidden by its access permissions.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/1855fd54-8283-4d57-ab22-4e818e22fcf7. Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. Visual Studio Token provider file not found at "D:\local\LocalAppData\.IdentityService\AzureServiceAuth\tokenprovider.json"
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/1855fd54-8283-4d57-ab22-4e818e22fcf7. Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. 'az' is not recognized as an internal or external command,
operable program or batch file.
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.GetAuthResultAsyncImpl(string resource, string authority, CancellationToken cancellationToken)
AzureServiceTokenProviderException: Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/1855fd54-8283-4d57-ab22-4e818e22fcf7. 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/1855fd54-8283-4d57-ab22-4e818e22fcf7. Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. An attempt was made to access a socket in a way forbidden by its access permissions. Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/1855fd54-8283-4d57-ab22-4e818e22fcf7. Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. Visual Studio Token provider file not found at "D:\local\LocalAppData\.IdentityService\AzureServiceAuth\tokenprovider.json" Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/1855fd54-8283-4d57-ab22-4e818e22fcf7. Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. 'az' is not recognized as an internal or external command, operable program or batch file.
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.GetAuthResultAsyncImpl(string resource, string authority, CancellationToken cancellationToken)
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.<get_KeyVaultTokenCallback>b__8_0(string authority, string resource, string scope)
FindEnBar.Program+<>c__DisplayClass2_0+<<SetupConfiguration>g__GetToken|0>d.MoveNext() in Program.cs
Microsoft.Azure.KeyVault.KeyVaultCredential.PostAuthenticate(HttpResponseMessage response)
Microsoft.Azure.KeyVault.KeyVaultCredential.ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
Microsoft.Azure.KeyVault.KeyVaultClient.GetSecretsWithHttpMessagesAsync(string vaultBaseUrl, Nullable<int> maxresults, Dictionary<string, List<string>> customHeaders, CancellationToken cancellationToken)
Microsoft.Azure.KeyVault.KeyVaultClientExtensions.GetSecretsAsync(IKeyVaultClient operations, string vaultBaseUrl, Nullable<int> maxresults, CancellationToken cancellationToken)
Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.LoadAsync()
Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.Load()
Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList<IConfigurationProvider> providers)
Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
Microsoft.Extensions.Hosting.HostBuilder.BuildAppConfiguration()
Microsoft.Extensions.Hosting.HostBuilder.Build()```

I got something similar after changing my acount password. After logging out and back in again in VS2019 or VS2022, the exception went away.

In the tutorial, it uses Azure Managed Identity to access Key Vault.
See the following code:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((ctx, builder) =>
{
var keyVaultEndpoint = GetKeyVaultEndpoint();
if (!string.IsNullOrEmpty(keyVaultEndpoint))
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));
builder.AddAzureKeyVault(
keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
}
}
).UseStartup<Startup>();
In your local development, it will use the user credential of VS or use the credential stored by Azure CLI.
However, in the cloud, you need to turn on the identity of your VM or Web App. And then add access policy for that identity in Key Vault.
Then, your code would be able to use Key Vault without any problem.

Related

(401) Unauthorized. When connecting to sharepoint site with App Only Authentication using PnP.Framework

I am trying to connect SharePoint in a console app using SharePoint App-Only Principal Authentication. I've registered the app by creating a clientId and clientSecret, grant the tenant scoped permission and trust. My permission request XML:
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />
</AppPermissionRequests>
I am using PnP.Framework for authentication but still give me an error 401 unauthorized.
My code are as follow:
using (var clientContext = new AuthenticationManager().GetACSAppOnlyContext(siteUrl, clientId, clientSecret))
{
var web = clientContext.Web;
clientContext.Load(web, w => w.Title);
clientContext.ExecuteQuery();
Console.WriteLine(web.Title);
};
The error I get is:
Unhandled exception. System.Net.WebException: The remote server returned an error: (401) Unauthorized.
at System.Net.HttpWebRequest.GetResponse()
at Microsoft.SharePoint.Client.SPWebRequestExecutor.Execute()
at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)
at Microsoft.SharePoint.Client.ClientRequest.ExecuteQuery()
at Microsoft.SharePoint.Client.ClientRuntimeContext.ExecuteQuery()
at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
Any help will be appreciated.

ITfoxtec - ADFS SAML2 The remote certificate is invalid according to the validation procedure

I am new to SAML2 authentication and have tried using ITfoxtec. Im getting this error when i run my app
AuthenticationException: The remote certificate is invalid according
to the validation procedure.
System.Net.Security.SslStream.StartSendAuthResetSignal(ProtocolToken
message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo
exception)
HttpRequestException: The SSL connection could not be established, see
inner exception.
System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream
stream, SslClientAuthenticationOptions sslOptions, CancellationToken
cancellationToken)
WebException: The SSL connection could not be established, see inner
exception. The remote certificate is invalid according to the
validation procedure. System.Net.HttpWebRequest.GetResponse()
i am ussing a generated certificate using OpenSSL and installed the pfx cert in the Trusted Root CA store in MMC. im not sure why its still causing me errors. I have also added the app as a Relying trust party in my ADFS already.## Heading ##
this is the snippet of my StartUp.cs
services.Configure<Saml2Configuration>(Configuration.GetSection("Saml2"));
services.Configure<Saml2Configuration>(saml2Configuration =>
{
//saml2Configuration.SignAuthnRequest = true;
saml2Configuration.SigningCertificate = CertificateUtil.Load(Configuration["Saml2:SigningCertificateFile"], Configuration["Saml2:SigningCertificatePassword"]);
//saml2Configuration.SigningCertificate = CertificateUtil.Load(AppEnvironment.MapToPhysicalFilePath(Configuration["Saml2:SigningCertificateFile"]), Configuration["Saml2:SigningCertificatePassword"]);
var entityDescriptor = new EntityDescriptor();
entityDescriptor.ReadIdPSsoDescriptorFromUrl(new Uri(Configuration["Saml2:IdPMetadata"]));
if (entityDescriptor.IdPSsoDescriptor != null)
{
saml2Configuration.AllowedIssuer = entityDescriptor.EntityId;
saml2Configuration.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.First().Location;
saml2Configuration.SingleLogoutDestination = entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.First().Location;
saml2Configuration.SignatureValidationCertificates.AddRange(entityDescriptor.IdPSsoDescriptor.SigningCertificates);
if (entityDescriptor.IdPSsoDescriptor.WantAuthnRequestsSigned.HasValue)
{
saml2Configuration.SignAuthnRequest = entityDescriptor.IdPSsoDescriptor.WantAuthnRequestsSigned.Value;
}
}
else
{
throw new Exception("IdPSsoDescriptor not loaded from metadata.");
}
});
services.AddSaml2();
and this is my appsettings.json
"Saml2": {
"IdPMetadata": "adfs url/FederationMetadata/2007-06/FederationMetadata.xml",
"Issuer": "saml_Example",
"SingleSignOnDestination": "http://adfs url/adfs/ls/",
"SignatureAlgorithm": "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
"SigningCertificateFile": "cert.pfx",
"SigningCertificatePassword": "pw",
"CertificateValidationMode": "None",
"RevocationMode": "NoCheck"
},
According to the error your machine/server do not trust the AD FS SSL/TLS certificate.
You have configured "IdPMetadata": "adfs url/FederationMetadata/2007-06/FederationMetadata.xml". It should be a real URL like https://....

How to disable ssl certificate validation upon OpenId connect in .Net Core 3.1?

I'm trying to connect in a development environment to a open id authority with it's ip address. Obviously in this scenario the ssl validation will fail. I'd like to bypass it, without any luck so far. I've found the following answers regarding this topic:
Setting the RequireHttpsMetadata to false in the OpenIdConnectOptions class.
Using the code below:
ServicePointManager.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;
When my app tries to access the oidc authority I recieve the same error:
An unhandled exception occurred while processing the request.
AuthenticationException: The remote certificate is invalid according
to the validation procedure.
System.Net.Security.SslStream.StartSendAuthResetSignal(ProtocolToken
message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo
exception)
HttpRequestException: The SSL connection could not be established, see
inner exception.
System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream
stream, SslClientAuthenticationOptions sslOptions, CancellationToken
cancellationToken)
IOException: IDX20804: Unable to retrieve document from:
'https://172.11.0.11:1111/MY_APP/.well-known/openid-configuration'.
Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(string
address, CancellationToken cancel)
InvalidOperationException: IDX20803: Unable to obtain configuration
from:
'https://172.11.0.11:1111/MY_APP/.well-known/openid-configuration'.
Microsoft.IdentityModel.Protocols.ConfigurationManager.GetConfigurationAsync(CancellationToken
cancel)
Warning: only use this during development. You need a custom certificate validation routine for your production platform if appropriate.
You might have overridden the wrong HttpClientHandler. Back-channel HttpClient for OpenId Connect can be overridden here:
services
.AddAuthentication(options =>
{
...
})
.AddCookie()
.AddOpenIdConnect(options =>
{
...
HttpClientHandler handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
options.BackchannelHttpHandler = handler;
});

Why have I UnauthorizedAccessException when I use Service Bus MessagingFactory?

I have configured authorization via certificate. When I use NamespaceManager to GetSubscription works fine, but when I try execute any method from MessagingFactory I receive System.UnauthorizedAccessException.
string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
SubscriptionDescription subscriptionDescription = namespaceManager.GetSubscription("testTopic", "testSubscription"); // executed properly
var messagingFactory = MessagingFactory.CreateFromConnectionString(connectionString);
var exist = namespaceManager.TopicExists("TestTopic"); // throws exception
Stack trace:
System.UnauthorizedAccessException was unhandled
HResult=-2147024891
Message=The remote server returned an error: (401) Unauthorized. Authorization failed for specified action: Manage..TrackingId:d8648c5a-5185-41c8-b787-72332403b7d9_*******,TimeStamp:2014-07-14 08:34:22
Source=Microsoft.ServiceBus
What's the matter?
For use NamespaceManager you must be in ManageUsers in Service Bus Namespace. To add user to existing namespace you can use ps Set-SBNamespace
You must be in the ManageUsers list in Service Bus Namespace or have the Authorization rule that gives you the Manage right on the Topic that you are getting the subscriptions for.

NOAUTH Authentication required

After i configured redis with password protected i get below error
Exception Occured
Exception Message --> NOAUTH Authentication required.
Exception Cause --> redis.clients.jedis.exceptions.JedisDataException: NOAUTH Authentication required.
File Name : SecurityInterceptor.java
Class Name : org.tcs.com.security.filter.SecurityInterceptor
Method Name : doFilter
redis.clients.jedis.exceptions.JedisDataException
indicates that jedis (a java Redis client) is used to connect with Redis server.
"NOAUTH Authentication required error"
indicates that the jedis connection requires password for authentication.
The following java code snippet shows how the password could be set:
JedisShardInfo shardInfo = new JedisShardInfo(redisHost, redisPort);
shardInfo.setPassword(redisPassword);
Jedis jedis = new Jedis(shardInfo);
jedis.connect();
Add your password property to the block in your Tomcat context.xml..
public JedisPool(final Config poolConfig, final String host, int port,
int timeout, final String password) {
this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE);
}
This method maybey help you.
The message is misleading. Proposal is
Error NOAUTH - Authentication required
String cacheHostname = "your cash host";
String cachekey = "your cash primary key";
JedisShardInfo shardInfo = new JedisShardInfo(cacheHostname, 6379);
shardInfo.setPassword(cachekey);
Jedis jedis = new Jedis(shardInfo);
jedis.auth(cachekey);
jedis.connect();
System.out.println( "Cache Response : " + jedis.ping());