Cannot access remote SQL Server from IIS 7 web app - asp.net

I've been trying to move the database from an application to another server without success.
I'm getting the following error message when opening the web application:
"Login failed. The login is from an untrusted domain and cannot be used with Windows authentication."
The user is a domain user configured as identity in the app pool and also has full access rights on the SQL Server (I can access the DB remotely over SQL Server Management Studio).
I tried the following:
enabled the Do not require Kerberos preauthentication option in AD
added the SQL account to "Access this computer from network" Policy under Local Security Policy -> Local Policies -> User Rights Assignment -> Access this computer from network"
Added the entry "127.0.0.1 localhost" to local hosts file
The domain user is local admin on the web and database server.
Web.Config / App Settings:
<appSettings>
<add key="DBServer" value="remoteSQLDBHostName" /> -- previous: value="."
<add key="DBName" value="WebDB" />
<add key="DBProvider" value="System.Data.SqlClient" />
<add key="DBMetadataBase" value="res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl" />
</appSettings>
The connection string is build dynamically in the application (sample snippet):
var sqlBuilder = new SqlConnectionStringBuilder
{
DataSource = serverName,
InitialCatalog = databaseName,
IntegratedSecurity = true
};
var providerString = sqlBuilder.ToString();
var entityBuilder = new EntityConnectionStringBuilder
{
Provider = providerName,
ProviderConnectionString = providerString,
Metadata = String.Format(metadataBase, Constants.ModelName)
};
var connStr = entityBuilder.ToString();
return connStr;

Related

Ckfinder azure set backend programmatically

I would like to set Azure as backend for CKFinder and I want to read values (account, password) from AppSettings, not CKFinder setting for backend.
smthng like:
<add key="CKFinderBackendAccountName" value="**********" />
<add key="CKFinderBackendAccountKey" value="************" />
So far I have this code and I want only Azure account, password to be read from APPSettings. I see no corresponding property in ConnectorBuilder.
connectorBuilder.LoadConfig()
.SetLicense(licenceDomain, licenceKey)
.SetAuthenticator(customAuthenticator)
.SetRequestConfiguration(
(request, config) =>
{
config.LoadConfig();
var defaultBackend = config.GetBackend("azureBackend");}

IdentityServer3 - Client certificate validation

I have IdentityServer3 and I'm trying to run their original samples WebHost (minimal) as the server and Console Client Credentials Flow using Certificate as the client because I want to test that the client can validate against IdS3 by using a X509 Thumbprint instead of a shared secret to get an Access Token.
The problem I'm having is that I'm getting an error response: invalid_client.
Apparently, it's because IdS3 doesn't receive the certificate on the incoming request, so it considers that the token request is invalid (I tested this by adding a custom SecretParser and checking the environment parameter and there's no ssl.ClientCertificate value which is the one X509CertificateSecretParser uses to parse it).
I'm just running both projects in 2 different instances of Visual Studio into IIS Express without modifying anything else on the projects. Is there anything that I'm missing on this matter? What else should I need to setup in order to make this work?
The first thing you need to do is to enable client certificates in IIS Express.
You do this by editing this file:
.vs\config\applicationhost.config
Change
<access sslFlags="None" />
to
<access sslFlags="Ssl, SslNegotiateCert" />
Now IIS Express supports client certificates, but it checks if the certificate is trusted as well.
The sample certificate, Client.pfx, will not work out of the box.
You can either let Windows trust the issuer of this certificate (not reccomended) or you could load an existing certificate from the certificate store with code like this:
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
string thumb = "<thumbprint>";
X509Certificate2Collection cers = store.Certificates.Find(X509FindType.FindByThumbprint, thumb, false);
X509Certificate2 cert = null;
if (cers.Count > 0)
{
cert = cers[0];
}
store.Close();
You will also need to put the thumbprint of this certificate into the ClientSecret property in the client list on the Identity Server.
This is the sample code you will need to change:
new Client
{
ClientName = "Client Credentials Flow Client",
Enabled = true,
ClientId = "clientcredentials.client",
Flow = Flows.ClientCredentials,
ClientSecrets = new List<Secret>
{
new Secret("secret".Sha256()),
new Secret
{
Value = "<your thumbprint here>",
Type = Constants.SecretTypes.X509CertificateThumbprint,
Description = "Client Certificate"
},
},
AllowedScopes = new List<string>
{
"read",
"write"
},
Claims = new List<Claim>
{
new Claim("location", "datacenter")
}
},

How to get an Authenticated Proxy Server working properly from ASP.NET app?

I have an ASP.NET 4.5 web app that calls an external web service. The environment requires internet access to go through an authenticated proxy server.
On my dev PC (Win7) the following configuration works fine.
<system.net>
<defaultProxy useDefaultCredentials="true" enabled="true">
<proxy usesystemdefault="True" autoDetect="True" />
</defaultProxy>
</system.net>
The above configuration doesn't work when applied to the test server. The test server is Windows Server 2008 with IIS 7. I have set the App Pool identity to be my user credentials so that proxy server would be authenticated using my credentials.
I am able to get the test server working with the proxy if I create a custom implementation of IWebProxy.
public class ManualProxy : IWebProxy
{
private readonly Uri _proxy;
private static readonly NameValueCollection AppSettings = ConfigurationManager.AppSettings;
public ManualProxy()
{
_proxy = new Uri(AppSettings["ManualProxy.Proxy"]);
}
#region IWebProxy
ICredentials IWebProxy.Credentials
{
get
{
return new NetworkCredential(AppSettings["ManualProxy.Username"], AppSettings["ManualProxy.Password"]);
}
set
{
throw new NotImplementedException();
}
}
Uri IWebProxy.GetProxy(Uri destination)
{
return _proxy;
}
bool IWebProxy.IsBypassed(Uri host)
{
return false;
}
#endregion
}
The configuration.
<defaultProxy useDefaultCredentials="false" enabled="true">
<module type="MyNamespace.ManualProxy, MyAssembly"/>
</defaultProxy>
The custom proxy is configured to authenticate using my credentials, which are the same credentials on my dev PC and for the IIS App Pool identity.
Ideally, I wouldn't need the custom proxy. How can I get the proxy server configured properly just using the existing options in the web.config?
Is there something that I'm not doing properly?
Forcing the proxy address rather than relying on auto detect fixed the issue.
<system.net>
<defaultProxy useDefaultCredentials="true" enabled="true">
<proxy usesystemdefault="False" autoDetect="False" proxyaddress="http://proxy:8080" />
</defaultProxy>
</system.net>

System.IO Exception: Logon failure: unknown user name or bad password

System.IO Exception: Logon failure: unknown user name or bad password.
1 minute ago | LINK
Hi All I am trying to resolve this issue with all possible solutions but could not succeed.
Requirement - I should be able to access XML file located in network share share folder for validation of users and other purposes.
Problem: I am able to access the XML file located in Network Share folder when debugging using VS 2010 but not when i published to IIS 7.
Methods Approached: I created a user account XXX and with password and made the user part of Administrators group. Set the website application pool identity to custome user account(XXX) created.
In the web.config I added a line:
<identity impersonate="true" userName="XXX" password="XXXXX"/>
Code where exception is caught-
string UserConfigXML ="\\\\servername\\Engineering\\Kiosk Back Up\\UserCFG.XML";
reader = new StreamReader(UserConfigXML);
string input = null;
string[] sArray;
while ((input = reader.ReadLine().Trim()) != "</USERS>")
{
if (input.Contains("<USER NAME="))
{
sArray = input.Split(new Char[] { '"' });
string sUserName = sArray[1].ToString().ToUpper();
string sDelivery = "";
while ((input = reader.ReadLine().Trim()) != ("</USER>"))
{
char[] array2 = new char[] { '<', '>' };
if (input.Contains("<DELIVERY_MECHANISM>"))
{
string[] mechanism = input.Split(array2);
sDelivery = mechanism[2].ToString().ToUpper();
if (sDelivery == "WEBMAIL")
{
UsersList.Add(sUserName);
}
}
}
}
}
return UsersList;
Any ideas how to resolve the issue?.
I propose 3 fixes for 2 different scenarios:
If you have both computers (server & computer holding the xml) hooked up using domain authentication: create a domain user and give it rights to access that file in the computer holding the xml.
Any other situation than the one mentioned above: create a user with the same name and password on both computers and set that as the one impersonated by the application pool.
(UNSECURE) Works in any scenario, without impersonation: put the XMLs in a network share that allows anonymous access.

Impersonation WCF

I have a WCF service, hosted in IIS, which I require to impersonate the annon account.
in my Webconfig
<authentication mode="Windows"/>
<identity impersonate ="true"/>
Testing the following, with vs2008
public void ByRuleId(int ruleId)
{
try
{
string user = WindowsIdentity.GetCurrent().Name;
string name = Thread.CurrentPrincipal.Identity.Name;
........
//get the data as a string.
using (FileStream fs = File.Open(location, FileMode.Open))
using (StreamReader reader = new StreamReader(fs))
{
rawData = reader.ReadToEnd();
}
}
catch.....
}
this works. however if I add impersonation attribute
[OperationBehavior(Impersonation=ImpersonationOption.Required)]
public void ByRuleId(int ruleId)
this does not work with the error message
"Either a required impersonation level was not provided, or the provided impersonation level is invalid."
a little poking around I noticed the first way was authenticated by Kerboros and the second way just failed on authentication type
I am using the WCF client tool, to pass my credentials. this seems to be working.
Check the 'TokenImpersonationLevel' of identity of the current thread; you'll need it to be at least 'Impersonation' to perform operations on the machine that the service is running on.
Typically, if you are using a proxy client, you'll need to set the 'TokenImpersonationLevel' of the client:
http://www.devx.com/codemag/Article/33342/1763/page/4
the main goal of this was to get anon access, even tho MattK answer was a great help.
here is what i did to do so.
on the implementation of the WCF contract I added the
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class TransferFile : ITransferFile
and in the web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled ="true" />
after this i was able to impersonate the anon account

Resources