Can't create azure blob container on storage emulator - azure

I'm unable to create a container while using Azure Storage Emulator from my c# .NET code.
I am using:
var container = serviceClient.GetContainerReference("media");
container.CreateIfNotExists();`
It return the error Error:
System.AggregateException: One or more errors occurred. ---> Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (403) Forbidden. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
at System.Net.HttpWebRequest.GetResponse()

Add the following line:
request.UseDefaultCredentials = true;
This will let the application use the credentials of the logged in user to access the site. If it's returning 403, clearly it's expecting authentication.
It's also possible that you (now?) have an authenticating proxy in between you and the remote site. In which case, try:
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
You could set a connection string to the storage emulator in an app.config:
<appSettings>
<add key="StorageConnectionString" value="UseDevelopmentStorage=true" />
</appSettings>
If you want to connect to storage emulator using account name and key, you would need to provide additional details like different endpoints.
var connectionString = #"DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;
AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;
BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;
TableEndpoint=http://127.0.0.1:10002/devstoreaccount1;
QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;";
This value is identical to the shortcut shown above, UseDevelopmentStorage=true.

Related

Where to find the Azure AD Auth Failure logs?

I have problem authenticating with Azure AD occasionally. I get the error that shown at the bottom of the page.
I set the following
IdentityModelEventSource.ShowPII = true;
to see the logs to find out what configuration that I'm missing. Where can I see the logs?
I'm running the WebAPI locally on my machine and the URL is https://localhost:16135/weatherforecast. I get the token via POSTMAN which is succeeding but using that token to execute the WebAPI is failing with the error.
This is the error that I see:
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
---> System.IO.IOException: IDX20804: Unable to retrieve document from: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
---> System.Net.Http.HttpRequestException: No such host is known.
---> System.Net.Sockets.SocketException (11001): No such host is known.
The error says "No such host in known"
If you are making a call to the WebAPI from outside your local machine. Then it will not find localhost.
Try using the name of your machine in the uri.

System.Private.CoreLib: Exception while executing function: System.Data.SqlClient: Keyword not supported: 'authentication'

I am writing a function to log information from every file uploaded to a blob storage account using entity framework core. When I try to connect to the azure sql db, I get the following error:
System.Private.CoreLib: Exception while executing function: BlobStorageLogging. System.Data.SqlClient: Keyword not supported: 'authentication'
I copied my connection string from the azure portal:
"DefaultConnection": {
"ConnectionString": "Server=tcp:dbserver.database.windows.net,1433;Initial Catalog=loggingdb;Persist Security Info=False;User ID={*****};
MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication=\"Active Directory Integrated\";",
"ProviderName": "System.Data.SqlClient"
}
The code that is causing the error is:
var optionsBuilder = new DbContextOptionsBuilder<LoggingDBContext>();
var options = optionsBuilder.UseSqlServer(connectionString, providerOptions => providerOptions.CommandTimeout(60)).Options;
using (var context = new LoggingDBContext(options))
{
context.Database.ExecuteSqlCommand("TRUNCATE TABLE [dbo].[BlobInfo]");
I have tried removing the authentication but that resulted in an unauthorized error. Any help would be appreciated.
The exception is expected for now, check the thread.
SqlClient for .NET Core still does not support using the 'authentication' keyword in the connection string. That will happen when this issue is actually fixed.
In order to use AAD in the new version of SqlClient in .NET Core 2.2, customers need to obtain the access token themselves using ADAL.NET and then set the AccessToken property on the SqlConnection
It means in .NET Core, Active Directory Integrated authentication is unavailable, to use Active Directory password authentication, we have to obtain access token which seems not ideal in EF configuration.
The workaround is to use Connection string for SQL authentication.

Azure SAS Token for Webjob DashboardConnectionString and StorageConnectionString

Azure web jobs want me to set AzureWebJobsDashboard and AzureWebJobsStorage properties on startup but, i do not want to expose AccountKey in code.
When I try to use SAS Token, JobHostConfiguration class trying to parse SAS Token and throws exception
var config = new JobHostConfiguration();
config.DashboardConnectionString = ConfigurationManager.GetSetting(KeyVaultSecrets.StorageReadWriteConnectionString);
config.StorageConnectionString = ConfigurationManager.GetSetting(KeyVaultSecrets.StorageReadWriteConnectionString);
Exception
System.InvalidOperationException occurred
HResult=0x80131509
Message=Failed to validate Microsoft Azure WebJobs SDK Dashboard connection string. The Microsoft Azure Storage account connection string is not formatted correctly. Please visit http://msdn.microsoft.com/en-us/library/windowsazure/ee758697.aspx for details about configuring Microsoft Azure Storage connection strings.
Source=
StackTrace:
at Microsoft.Azure.WebJobs.Host.Executors.StorageAccountParser.ParseAccount(String connectionString, String connectionStringName, IServiceProvider services)
at Microsoft.Azure.WebJobs.Host.Executors.DefaultStorageAccountProvider.set_DashboardConnectionString(String value)
Is there any way to use SAS Token while creating configuration for JobHostConfiguration?
SAS tokens are not yet supported here. However, you don't need to put the connection strings in your code. You should be placing them in appsettings instead! Like so:
<configuration>
<connectionStrings>
<!-- The format of the connection string is "DefaultEndpointsProtocol=https;AccountName=NAME;AccountKey=KEY" -->
<!-- For local execution, the value can be set either in this config file or through environment variables -->
<add name="AzureWebJobsDashboard" connectionString="xxxxxxx" />
<add name="AzureWebJobsStorage" connectionString="yyyyyyyyy" />
</connectionStrings>
And furthermore, you can then set your appsettings directly on your site.
That said, in the latest nightly builds, we now have support for running [Timer] and [Singleton] on SAS connection strings; and you can disable logging by explicitly setting config.DashboardConnectionString to null. But we don't yet have support for binding [Blob] and other storage to SAS urls. See the unit test from this commit: https://github.com/Azure/azure-webjobs-sdk/blob/bd2d9ea34f13fc16569e8d8f80bafdb605eeb6f9/test/Microsoft.Azure.WebJobs.Host.EndToEndTests/InternalStorageTests.cs
We can use the SAS in a connection string. Because the SAS contains the information required to authenticate the request, a connection string with a SAS provides the protocol, the service endpoint, and the necessary credentials to access the resource according to that link
In this way, StorageAccountParser.ParseAccount(String connectionString) can parse the connection string
BlobEndpoint=https://storagesample.blob.core.windows.net;
SharedAccessSignature=sv=2015-04-05&sr=b&si=tutorial-policy-635959936145100803&sig=9aCzs76n0E7y5BpEi2GvsSv433BZa22leDOZXX%2BXXIU%3D

Can not connect to Azure SQL Server using Active directory integrated authentication in AppService

We have web application deploy on Azure App Service. Our database is also on Azure which is configured to use AAD authentication (We have assigned AAD Admin).
We are using below connection string in web app to connect to this server and database using below connections string.
Data Source=xxxxxxx.database.windows.net;Initial
Catalog=xxxxxxx;Persist Security Info=False;Authentication=Active
Directory Integrated
Please note: This connection string is working fine when using thru local system. But getting below error when we use this conn string in Azure App Service:
Failed to authenticate the user NT Authority\Anonymous Logon in Active
Directory (Authentication=ActiveDirectoryIntegrated). Error code
0x4BC; state 10 The format of the specified domain name is invalid
According to your description, I found you used the Active Directory integrated authentication.
To use integrated Windows authentication, your domain’s Active Directory must be federated with Azure Active Directory. Your client application (or a service) connecting to the database must be running on a domain-joined machine under a user’s domain credentials
If you published the web app to Azure, Azure's web app server will not be in your domain’s Active Directory. So the SQL server will not pass the auth.
I suggest you could try to use Active Directory password authentication instead of the Active Directory integrated authentication.
Replace the connection string as below use azure AD user name and password. It will work well.
Server=tcp:brandotest.database.windows.net,1433;Initial Catalog=bradnotestsql;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication="Active Directory Password";
Since the accepted answers are a bit dated, if you are out here in 2020 or later, the correct way for setting up integrated authentication is as follows:
(excerpted from here, the asp.net standard implementation)
https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi
add the Microsoft.Azure.Services.AppAuthentication nuget package.
modify your web.config by adding: (in configSections)
<section name="SqlAuthenticationProviders" type="System.Data.SqlClient.SqlAuthenticationProviderConfigurationSection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
(and then)
<SqlAuthenticationProviders>
<providers>
<add name="Active Directory Interactive" type="Microsoft.Azure.Services.AppAuthentication.SqlAppAuthenticationProvider, Microsoft.Azure.Services.AppAuthentication" />
</providers>
</SqlAuthenticationProviders>
It's important to pay attention to the name you use there. Then... your connection string will look like:
<add name="MyEntities" connectionString="metadata=res://*/Data.MyDB.csdl|res://*/Data.MyDB.ssdl|res://*/Data.MyDB.msl;provider=System.Data.SqlClient;provider connection string="server=tcp:MyDB.database.windows.net;database=MyDB;UID=AnyString;Authentication=Active Directory Interactive;"" providerName="System.Data.EntityClient" />
The important notes are that the name you specify in the SqlAuthenticationProviders section must be the exact same name you use in the connection string for Authentication.
The other important note is that, coming from your old connection strings, you have to change Data Source to be Server, and Initial Catalog to be Database. UID=AnyString is necessary, or an exception is thrown.
Failure to follow these steps exactly will net you a lovely error:
System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> AdalException: The format of the specified domain name is invalid.\r\n at ADALNativeWrapper.ADALGetAccessToken(String username, IntPtr password, String stsURL, String servicePrincipalName, ValueType correlationId, String clientId, Boolean* fWindowsIntegrated, Int64& fileTime)\r\n at System.Data.SqlClient.ActiveDirectoryNativeAuthenticationProvider.<>c__DisplayClass2_0.b__0()\r\n at System.Threading.Tasks.Task`1.InnerInvoke()\r\n at System.Threading.Tasks.Task.Execute()\r\n --- End of inner exception stack trace
At the first the error doesn't make sense, but once you see that the parameters were renamed from Data Source to Server, it does make sense.
Maybe all you need to use is token (certificate) authentication as explained on below resource:
https://github.com/Microsoft/sql-server-samples/tree/master/samples/features/security/azure-active-directory-auth/token
Try to register your application with Azure Active Directory as explained on that resource.
Hope this helps.

ASp.net Web Application Connection string issue

I have a old application and the other developer was using connection string like this
<add key="test" value="Data Source=Serzero;Database=NijaDatabase;trusted_connection=true;Connect Timeout=360"/>
My question is that the application is ruining perfectly on the local server access remote database when i am using VS2010 but when i am hosting this my application on the IIS on my machine getting error ...Locally applicaiton working fine login logout everything but on IIS getting this error when try to log in
Login failed for user
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Login failed for user .
Source Error:
You need to either add Integrated Security=False;User Id=userid;Password=password to your connection string.

Resources