Impersonate settings in config for multiple databases - c#-4.0

I have a console application which connects to two different SQL databases. I'm using the "impersonate" tag within the config file to force the application to login as "APP_USER". The APP_USER account utilizes windows authentication & has been granted permissions in both databases.
The first DB connection works fine, but the second one fails as it is trying to log in as my account which does not have access.
System.Data.SqlClient.SqlException: Login failed for user 'DOMAIN\CURRENT_USER'.
What do I need to change in my config to make the application login to both databases as another user?
<configuration>
<connectionStrings>
<add name="Connection1" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=DB1;initial catalog=DBcat1;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="Connection2" connectionString="metadata=res://*/Models.Model2.csdl|res://*/Models.Model2.ssdl|res://*/Models.Model2.msl;provider=System.Data.SqlClient;provider connection string="data source=DB2;initial catalog=DBcat2;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.web>
<identity impersonate="true" userName="DOMAIN\APP_USER" password="password"/>
</system.web>
</configuration>

Apparently the config-setting route can only be used in asp.net projects. In order to accomplish this within a console application, you have to write code that utilizes LogonUser within the advapi32.dll library.
Similar question: StackOverflow: Windows Impersonation from C#
I based my final code off of the following project: Code Project: A small C# Class for impersonating a User
Everything seems to be working fine now.

Related

ASP.Net MVC 5 Windows Authentication

I know that this has been asked before here, but I couldn't find a way to fix this. I'm using VS 2022/MVC 5/IISExpress and these are my configs:
web.config:
<authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
And these lines in my vbproj file:
<IISExpressAnonymousAuthentication>disabled</IISExpressAnonymousAuthentication>
<IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>
According to the approved solution in this post the above should work, but doesn't. I am logged in to Windows using my domain account and have been added to local administrators group (Of course I'm not a domain admin, just a standard user). I can login to my web app using my own domain account, but not with other domain accounts (I have tried two different accounts). Any credentials other than mine is rejected by application. How can I fix it?

How to cleanly automate authentication for Azure Devops feeds?

Presumably there are lots of companies who are facing the same struggle we are.
For any microservice, before running a dotnet restore we need to first ensure we've successfully configured our ADO package feeds with an active token.
To achieve this we have a script which downloads and runs the CredentialProvider.VSS.exe (as suggested by Microsoft), using the output to build credentials which then register the feeds on the user's computer. This needs to happen daily as the tokens generated will expire.
The script above is ugly and worse yet, every repository needs it in order to ensure feeds are configured with active tokens. Even if we moved the ugly script to a PowerShell module for example, how would we authenticate against the PS feed in order to download that module?
I don't see why the CredentialProvider is neccessary, why can't nuget just prompt us for credentials whenever our token expires? Has anyone come up with a cleaner solution out there which manages authentication to ADO feeds across multiple repositories?
How to cleanly automate authentication for Azure Devops feeds?
To authentication for Azure Devops feeds, you could try to use the NuGet authenticate task, which configure NuGet tools to authenticate with Azure Artifacts and other NuGet repositories.
Then we could create a new NuGet service connection with PAT:
You can use a longer-term PAT for certification, so you don't have to change certification every day.
another approach using nuget.confg as below
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="AzureDevOpsFeed" value="https://pkgs.dev.azure.com/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/index.json" />
<add key="nuget" value="https://xxxxxxxxxxxxxxxxxxxxx/index.json" />
</packageSources>
<packageSourceCredentials>
<VSTSFeed>
<add key="UserName" value="#{PAT_UserName}#" />
<add key="ClearTextPassword" value="#{PersonalAccessToken}#" />
</VSTSFeed>
</packageSourceCredentials>
</configuration>

How To Password Protect a Static Site in Azure

I have a static site (i.e all html files, no .Net project) that is being hosted in Azure. I'm trying to password protect this site. I've read that I could create a custom authorisation module, which I've done, but I can't install this as I need to run a appcmd.exe command to allow the correct bit of the web.config to be edited.
Either; how can I password protect a static azure site, or how can I take advantage of the features of the ServiceDefinition.csdef without having a visual studio project?
On the management portal, you can configure that your site needs to use credentials. Credentials are managed via the Azure portal if you use this method.
You could use Forms Authentication which should be pretty straightforward to implement and won't require any startup task (necessary to run appcmd.exe).
Set your application to use forms authentication in your web.config.
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="/myadminlogin.aspx" protection="All" path="/" timeout="120" />
</authentication>
Define the protected folders in your web.config.
<location path="secure">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
Within your login area check a condition and set the auth cookie:
'SET AUTH COOKIE
FormsAuthentication.SetAuthCookie(sessionID, False)
response.redirect(/secure/securearea.html)
This unfortunately is the one page where you will need some server side code.

ImageOptimizations\App_Sprites\blank.gif Access is denied

To optimize the images and automatically generate CSSprites use a microsoft package called Sprite Optimization and Image Preview 4
Error
Locally everything works perfectly, but to publish my site the following error occurs:
Access to the path 'D:\Hosting\8399780\html\dev\App_Sprites\blank.gif' is denied.
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.UnauthorizedAccessException: Access to the path 'D:\Hosting\8399780\html\dev\App_Sprites\blank.gif' is denied.
ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
To grant ASP.NET access to a file, right-click the file in Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.
Attempt
In an attempt to resolve the problem within 'App_Sprites' folder, added the following web.config:
<?xml version="1.0"?>
<configuration>
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
<system.webServer>
<security>
<authorization>
<add accessType="Allow" users="*" />
</authorization>
</security>
</system.webServer>
</configuration>
'blank.gif' image is not used anywhere in my application!
Inside the App_Sprites folder there are a only one subfolder called hire;
I believe that this framework is trying to write a blank.gif file to that directory. You need to give the account under which the IIS app pool runs write access to that folder in windows.

SharePoint and <identity impersonate="false" />

I would like to use integrated authentication to access a SQL database from a web part. It should use the IIS Application pool identity.
By default you will get the error:
System.Data.SqlClient.SqlException: Login failed for user 'SERVER\IUSR_VIRTUALMACHINE'.
Because in web.config impersonation is set to true:
<identity impersonate="true" />
I can set this to false and the database code will work. Anonymously accessed sites will also work. Any SharePoint site that uses authentication will fail however so this is not really a solution..
To solve this would I have to encapsulate all my database access code to run with elevated priviliges, is that how SharePoint does it internally? Somehow that doesn't seem like the most performant solution.
Is that still the way to go, just use SQL security to access databases from SharePoint custom web parts?
The <identity /> and <authentication /> elements in the web.config file will together determine the account that is used in to connect to SQL Server when using integrated authentication.
When <authentication mode="Windows" /> is configured, you're deferring to IIS to authenticate users. I'm guessing that your your web.config contains:
<authentication mode="Windows" />
<identity impersonate="true" />
and that IIS is configured to allow anonymous users. Setting <identity impersonate="true" /> causes IIS to pass the identity of the IIS anonymous access account to SQL Server.
As Lars point out, using SPSecurity.RunWithElevatedPrivileges will achieve what you want. I don't believe you'll see any noticeable impact on performance but that's something you can test :-)
Use SPSecurity.RunWithElevatedPrivileges to run your code in the context of the app pool identity.
This is incorrect. Because <identity impersonate="true" /> is set to true ASP.NET / IIS will run the thread as the user that is currently logged in (so not the app pool account but the actual user logged into the website).
Something else is going on here. Could you post your connection string for the custom database? (minus the private data off course)

Resources