I have added the following settings inside my web.config file to initiate an API call to external system. So I am storing the API URL + username + password as follows:-
<appSettings>
<add key="ApiURL" value="https://...../servlets/AssetServlet" />
<add key="ApiUserName" value="tmsservice" />
<add key="ApiPassword" value="test2test2" />
Then inside my action method I will be referencing these values when building the web client as follows:-
public ActionResult Create(RackJoin rj, FormCollection formValues)
{
XmlDocument doc = new XmlDocument();
using (var client = new WebClient())
{
var query = HttpUtility.ParseQueryString(string.Empty);
foreach (string key in formValues)
{
query[key] = this.Request.Form[key];
}
query["username"] = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiUserName"];
query["password"] = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiPassword"];
string apiurl = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiURL"];
But in this was I will be exposing the username and password and these can be captured by users, so my question is how I can secure the API username and password?
You can encrypt the web.config with aspnet_regiis. This is to stop people with access to your server from reading sensitive information.
By the way, I would put your config settings inside a class, that can then be injected into your controllers - it will make unit testing easier.
Generally, web.config is a secure file and IIS does not serve it, therefore it will not be exposed to users who are making requests to web server. Web server only serves specific type of files and web.config is surely not one of 'em.
Quite often you save your database connection string in it which includes password. Now imagine an scenario where web.config was not secure. You have created a major security threat to your application.
Therefore, specially as long as your project is not too big, you should not be worrying about it.
Yet, you may have a better approach but creating a project called "Resources" and save all the critical information such as settings, consts, enums and etc in there. That would be a slick and organized approach.
If you are passing the username/password over the wire though (for example in case of a secured API call), you may want to use https to make sure that information that are travelling are encrypted but that has nothing to do with the security of web.config file.
I know this may sound like over engineering, but if you can, you really should use a secret management service, such as AWS Secrets Manager or Azure Key Vault.
By storing your passwords, even in encrypted form, in your web.config or app.config, you creating several problems for yourself:
now your encrypted passwords are going to be committed to your source control, making them accessible to anyone with the read access. To get rid of them properly, you'll need to do a history rewrite (if you are using git) which is a major pain
while you technically can put your passwords in the machine-level config, and outside of the source control, you'll need to update all those files when your password changes
anyone who's got your encrypted password now can try to decrypt it, using either aspnet_regiis.exe tool (if that's what you used to encrypt it), or if you rolled your own security, reverse engineer that using your source code, figuring out what decryption algo & key it is using
whenever you need to change a password, you'll need to make changes to that file & re-deploy the application.
On the other hand, when you use a secret management service, no secrets or decryption key or algorithm is stored in your source code. Retrieving a secret is as simple as this:
For Azure Key Vault:
var keyVaultUrl = "https://<your-key-vault-name>.vault.azure.net/";
var credential = new DefaultAzureCredential();
var client = new SecretClient(vaultUri: new Uri(keyVaultUrl), credential);
KeyVaultSecret secret = client.GetSecret("<your-secret-name>");
Console.WriteLine($"{secret.Name}: {secret.Value}");
For AWS Secrets Manager (skipped some error handling code):
var client = new AmazonSecretsManagerClient(accessKeyId, secretAccessKey,
RegionEndpoint.APSoutheast2);
var request = new GetSecretValueRequest {
SecretId = secretName
};
GetSecretValueResponse response = null;
response = client.GetSecretValueAsync(request).Result;
This approach has lots of advantages over storage of local secrets:
you don't have to mess with storing different values in configs for Prod/Staging/Dev environments -- just read appropriately named secrets (such as '[Dev|Prod|Stag]DBPassword`
only selected few people can have access to the very important secrects (such as, I dunno, say Transfer all $$$ from Deus account to all E-Coin wallets everywhere authorisation code)
if anyone steals your source code (disgruntled employee, accidental leak) non of your passwords have been leaked
changing a password is easy -- you just update it using the could management console and restart the app(s)
I have written a couple of articles, showing how to set up and read secrets with AWS and Azure on my blog, feel free to check it out if you need step-by-step directions and complete source code:
How to use AWS Secrets Manager to store & read passwords in .Net Core apps
How to securely store and retrieve sensitive info in .NET Core apps with Azure Key Vault
The web.config file is just a file on the file system and so you should (mostly) consider its security in the same way as you would any other file. It will not be served by IIS (unless you make a frankly insane config change to IIS - easy to check for, just try and request it with a browser)
It is good practice to secure your website directory (c:/sites/my-site-here or whatever) using folder permissions to just the website app domain user to read the files (and the deployment user if needed) by using normal windows file permissions
So it may not be necessary to encrypt if you have confidence in the security of the web server. However if you are say on shared hosting, or selling the website code, or the source code is public, then it might be wise to encrypt it. it is a little bit hassle some though.
Why use Web.config?
One of the advantages of having data in Web.config as opposed to storing it in Constants, Enums, etc... is that you can change the data for different environments easily.
Protecting data
The best way to secure the data in Web.config is to encrypt them. Instead of encrypting entire sections in the config file as suggested by Joe and user1089766 you can just encrypt the password string and store it in the config.
Retrieving data
You can use a helper function such as the one below to decrypt the keys.
private const readonly string decryptKey = "";
public string GetFromConfig(string key)
{
var encryptedText = System.Web.Configuration.WebConfigurationManager.AppSettings[key];
var plainText = Decrypt(encryptedText, decryptKey);
return plainText;
}
In this way the decryption key will be inside the project common for all environments. But you can change the data in the web.config easily without recompiling your app.
PS: You can change the decryptionKey and the corresponding data with each version to improve security.
I have to encourage you to separate the code from the Keys. Even if you encrypt the file, someone can clone it from your repo and while it is encrypted, you may no longer be able to track the file, or may get access to a key in the future, etc.
Plus as Art indicated (and maybe others in the thread) this makes it is really easy to have a separate set of keys for Dev / Test / Prod / etc. If you encrypt the file, sounds like you are going to either have the same encrypted data and decryption key in all of these environments. You won't necessarily have an easy way to change in one but not the others.
Think about the long game - not just passwords but other configuration information should be loaded and unique per environment (API Keys, etc.)
We use this approach for developers too. I don't want each developer to have their own API key, passwords, etc so they don't have access to systems they don't need. I can shutdown a user's API key if a development laptop is lost. I can rotate dev / test / prod API keys and only have to worry about changing in one place, not inform all users that a file has been updated and they need to re-clone.
Related
My web application is using WIF to authenticate users against their own STS (I have no control over how their STS is setup, I just give them the url to the federation metadata).
My web application is running over 2 load balancers with 2 servers behind them, I am also using sticky sessions with a 1hr timeout on them and both machines share the same machine key, I also have the LoadUserProfile set to true in IIS.
It seems to work fine when only 1 user is logged on using a unique STS but as soon as there are a more then one, I can see the following errors been logged on the server many times in a short period.
Key not valid for use in specified state.
Stack Trace: at System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope) at Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[] encoded)\r\n at System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope) at Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[] encoded)
How can I solve this error, or any help in diagnosing this issue?
For anyone looking for the same issue in the future, the information here fixed my issue. http://weblogs.asp.net/cibrax/the-system-cannot-find-the-file-specified-error-in-the-wif-fam-module (copy of the article below)
The Federation Authentication Module (FAM) shipped as part of WIF protects by the default the session cookies from being tampered with in passive scenarios using DPAPI. As I mentioned in the past, this technique simplifies a lot the initial deployment for the whole solution as nothing extra needs to configured, the automatically generated DPAPI key is used to protect the cookies, so this might be reason to have that as default protection mechanism in WSE, WCF and now WIF.
However, this technique has some serious drawbacks from my point of view that makes it useless for real enterprise scenarios.
If web application that relies on FAM for authenticating the users is hosted in IIS. The account running the IIS process needs to have a profile created in order to use DPAPI. A workaround for this is to log into the machine with that account to create the initial profile or run some script to do it automatically.
DPAPI is not suitable for web farm scenarios, as the machine key is used to protect the cookies. If the cookie is protected with one key, the following requests must be sent to the same machine. A workaround for this could be to use sticky sessions, so all the user requests from the same machine are handled by the same machine on the farm.
Fortunately, WIF already provides some built-in classes to replace this default mechanism by a protection mechanism based on RSA keys with X509 certificates.
The “SecuritySessionHandler” is the handler in WIF that is responsible for tracking the authentication sessions into a cookie. That handler receives by default some built-in classes that applies transformations to the cookie content, such as the DeflatCookieTransform and the ProtectedDataCookieTransform (for protecting the content with DPAPI). There are also two other CookieTransform derived classes that are not used at all, and becomes very handy to enable enterprise scenarios, the RSAEncryptionCookieTransform and RSASignatureCookieTransform classes. Both classes receives either a RSA key or X509 certificate that is used to encrypt or sign the cookie content.
Therefore, you can put the following code in the global.asax file to replace the default cookie transformations by the ones that use a X509 certificate.
protected void Application_Start(object sender, EventArgs e)
{
FederatedAuthentication.ServiceConfigurationCreated += new EventHandler<Microsoft.IdentityModel.Web.Configuration.ServiceConfigurationCreatedEventArgs>(FederatedAuthentication_ServiceConfigurationCreated);
}
void FederatedAuthentication_ServiceConfigurationCreated(object sender, Microsoft.IdentityModel.Web.Configuration.ServiceConfigurationCreatedEventArgs e)
{
var cookieProtectionCertificate = CertificateUtil.GetCertificate(StoreName.My,
StoreLocation.LocalMachine, "CN=myTestCert");
e.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(
new SessionSecurityTokenHandler(new System.Collections.ObjectModel.ReadOnlyCollection<CookieTransform> (
new List<CookieTransform>
{
new DeflateCookieTransform(),
new RsaEncryptionCookieTransform(cookieProtectionCertificate),
new RsaSignatureCookieTransform(cookieProtectionCertificate)
})
));
}
The only part of the code you will need to change is where it tries to find your certificate location on your server.
var cookieProtectionCertificate = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=myTestCert");
I have added the following settings inside my web.config file to initiate an API call to external system. So I am storing the API URL + username + password as follows:-
<appSettings>
<add key="ApiURL" value="https://...../servlets/AssetServlet" />
<add key="ApiUserName" value="tmsservice" />
<add key="ApiPassword" value="test2test2" />
Then inside my action method I will be referencing these values when building the web client as follows:-
public ActionResult Create(RackJoin rj, FormCollection formValues)
{
XmlDocument doc = new XmlDocument();
using (var client = new WebClient())
{
var query = HttpUtility.ParseQueryString(string.Empty);
foreach (string key in formValues)
{
query[key] = this.Request.Form[key];
}
query["username"] = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiUserName"];
query["password"] = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiPassword"];
string apiurl = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiURL"];
But in this was I will be exposing the username and password and these can be captured by users, so my question is how I can secure the API username and password?
You can encrypt the web.config with aspnet_regiis. This is to stop people with access to your server from reading sensitive information.
By the way, I would put your config settings inside a class, that can then be injected into your controllers - it will make unit testing easier.
Generally, web.config is a secure file and IIS does not serve it, therefore it will not be exposed to users who are making requests to web server. Web server only serves specific type of files and web.config is surely not one of 'em.
Quite often you save your database connection string in it which includes password. Now imagine an scenario where web.config was not secure. You have created a major security threat to your application.
Therefore, specially as long as your project is not too big, you should not be worrying about it.
Yet, you may have a better approach but creating a project called "Resources" and save all the critical information such as settings, consts, enums and etc in there. That would be a slick and organized approach.
If you are passing the username/password over the wire though (for example in case of a secured API call), you may want to use https to make sure that information that are travelling are encrypted but that has nothing to do with the security of web.config file.
I know this may sound like over engineering, but if you can, you really should use a secret management service, such as AWS Secrets Manager or Azure Key Vault.
By storing your passwords, even in encrypted form, in your web.config or app.config, you creating several problems for yourself:
now your encrypted passwords are going to be committed to your source control, making them accessible to anyone with the read access. To get rid of them properly, you'll need to do a history rewrite (if you are using git) which is a major pain
while you technically can put your passwords in the machine-level config, and outside of the source control, you'll need to update all those files when your password changes
anyone who's got your encrypted password now can try to decrypt it, using either aspnet_regiis.exe tool (if that's what you used to encrypt it), or if you rolled your own security, reverse engineer that using your source code, figuring out what decryption algo & key it is using
whenever you need to change a password, you'll need to make changes to that file & re-deploy the application.
On the other hand, when you use a secret management service, no secrets or decryption key or algorithm is stored in your source code. Retrieving a secret is as simple as this:
For Azure Key Vault:
var keyVaultUrl = "https://<your-key-vault-name>.vault.azure.net/";
var credential = new DefaultAzureCredential();
var client = new SecretClient(vaultUri: new Uri(keyVaultUrl), credential);
KeyVaultSecret secret = client.GetSecret("<your-secret-name>");
Console.WriteLine($"{secret.Name}: {secret.Value}");
For AWS Secrets Manager (skipped some error handling code):
var client = new AmazonSecretsManagerClient(accessKeyId, secretAccessKey,
RegionEndpoint.APSoutheast2);
var request = new GetSecretValueRequest {
SecretId = secretName
};
GetSecretValueResponse response = null;
response = client.GetSecretValueAsync(request).Result;
This approach has lots of advantages over storage of local secrets:
you don't have to mess with storing different values in configs for Prod/Staging/Dev environments -- just read appropriately named secrets (such as '[Dev|Prod|Stag]DBPassword`
only selected few people can have access to the very important secrects (such as, I dunno, say Transfer all $$$ from Deus account to all E-Coin wallets everywhere authorisation code)
if anyone steals your source code (disgruntled employee, accidental leak) non of your passwords have been leaked
changing a password is easy -- you just update it using the could management console and restart the app(s)
I have written a couple of articles, showing how to set up and read secrets with AWS and Azure on my blog, feel free to check it out if you need step-by-step directions and complete source code:
How to use AWS Secrets Manager to store & read passwords in .Net Core apps
How to securely store and retrieve sensitive info in .NET Core apps with Azure Key Vault
The web.config file is just a file on the file system and so you should (mostly) consider its security in the same way as you would any other file. It will not be served by IIS (unless you make a frankly insane config change to IIS - easy to check for, just try and request it with a browser)
It is good practice to secure your website directory (c:/sites/my-site-here or whatever) using folder permissions to just the website app domain user to read the files (and the deployment user if needed) by using normal windows file permissions
So it may not be necessary to encrypt if you have confidence in the security of the web server. However if you are say on shared hosting, or selling the website code, or the source code is public, then it might be wise to encrypt it. it is a little bit hassle some though.
Why use Web.config?
One of the advantages of having data in Web.config as opposed to storing it in Constants, Enums, etc... is that you can change the data for different environments easily.
Protecting data
The best way to secure the data in Web.config is to encrypt them. Instead of encrypting entire sections in the config file as suggested by Joe and user1089766 you can just encrypt the password string and store it in the config.
Retrieving data
You can use a helper function such as the one below to decrypt the keys.
private const readonly string decryptKey = "";
public string GetFromConfig(string key)
{
var encryptedText = System.Web.Configuration.WebConfigurationManager.AppSettings[key];
var plainText = Decrypt(encryptedText, decryptKey);
return plainText;
}
In this way the decryption key will be inside the project common for all environments. But you can change the data in the web.config easily without recompiling your app.
PS: You can change the decryptionKey and the corresponding data with each version to improve security.
I have to encourage you to separate the code from the Keys. Even if you encrypt the file, someone can clone it from your repo and while it is encrypted, you may no longer be able to track the file, or may get access to a key in the future, etc.
Plus as Art indicated (and maybe others in the thread) this makes it is really easy to have a separate set of keys for Dev / Test / Prod / etc. If you encrypt the file, sounds like you are going to either have the same encrypted data and decryption key in all of these environments. You won't necessarily have an easy way to change in one but not the others.
Think about the long game - not just passwords but other configuration information should be loaded and unique per environment (API Keys, etc.)
We use this approach for developers too. I don't want each developer to have their own API key, passwords, etc so they don't have access to systems they don't need. I can shutdown a user's API key if a development laptop is lost. I can rotate dev / test / prod API keys and only have to worry about changing in one place, not inform all users that a file has been updated and they need to re-clone.
I need to store and retrieve sensitive data from a local database - this data is used by a web application.
In order to protect said data I've opted to make use of the ProtectedData class.
The IIS application is running using a specific AD user (Identity property in the Advanced Settings).
Everything works fine until I do an IISRESET - at this point, it seems that the identity is changed for the purposes of the ProtectedData class, and I'm left with data I cannot decrypt - I'm getting a Key not valid for use in specified state exception.
Here's the code I'm using:
static public string Encrypt(string data)
{
var encryptedData = ProtectedData.Protect(System.Text.Encoding.UTF8.GetBytes(data), entropy, DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedData);
}
static public string Decrypt(string base64string)
{
var encryptedData = Convert.FromBase64String(base64string);
return System.Text.Encoding.UTF8.GetString(ProtectedData.Unprotect(encryptedData, entropy, DataProtectionScope.CurrentUser));
}
The entropy is obviously static for my application.
What's going on? I was under the impression that DataProtectionScope.CurrentUser will use, as the name implies, the current user - which should be, to my knowledge, the application pool identity. Why does it seem like this is changed when I perform an IISRESET?
Whilst I don't know why this was happening, I changed the code to use AES encryption instead - this is working fine.
While not an answer to the problem per-say I think it's a valid workaround that deserves mentioning.
EDIT:
I think I've found what was causing the issue (I still don't exactly know WHY this is happening, but I did notice something today).
If the web application is using the ApplicationPool identity, then all is fine and well and DPAPI should continue working after an IISRESET. However if I change the identity to a specific user defined in AD, then things go haywire after the application pool is recycled.
Lucky for me In this particular case I neither need a specific AD user any more and the main encryption is based on AES (DPAPI can't be used to access a shared resource when load balancing comes into the equation) with DPAPI only being used to encrypt the local copy of the AES keys.
I had the exact error when using ASP.NET Core Data Protection API, and for those of you who has this error, please confirm that LoadUserProfile was enabled for the Application Pool User.
A shopping cart application I'm working on jumps domain when it goes from the normal page into the submit-your-details page.
Long story short there are two copies of the application deployed: one server for the 'main' site and one server with an ev certificate running on https for the customer details (including payment; this is a PCI compliance issue).
My question is this:
When jumping from http://shop.domain -> https://secure.domain (and back, if the user browses back), how can I preserve the session?
Its trivial to pass cookies cross domain using JSONP, but I have no idea what to do with them on the remote side to 'reconnect' to the session.
I have read various things about rolling your own custom session provider, etc. etc. but I haven't found one that is more than just generic advice; certainly no examples of how this might be used to rejoin a session.
This is a for an MVC3 c# web app.
Problem with Session's is that they are kept in the same domain.
If you have the 2 applications in sub domains you can always append this to your web.config
<httpCookies domain=".domain.com"/>
and that will do the trick, but if the domains are completely different, the best way is always to roll out your own session provider or use an existing one, like SQL.
You can use for this any Caching System where instead of append variables into a session variable, you append them into the cache as key/value pair, you can always use a NoSQL alternative (plenty of free accounts out there so you can prototyping and make a proof of concept in order to roll out the final bits).
Memcached server is always a good alternative and Couchbase as the community version available for free.
The trick here is to do this:
Cache.AddObject(key + "UserInfo-name", "Bruno Alexandre");
where key could be a query string value appended in global.asax upon session_start
instead of this
Session["UserInfo-name"] = "Bruno Alexandre";
When you create cookie then you must write
Response.AppendCookie("Your cookie name");
To get that the code is something like
if (Request.Cookies["Your cookie name"] != null)
{
string value = Request.Cookies["Your cookie name"].Value;
}
and if there are different solutions then find
machineKey
which need to be same. you get it under
system.web in web.config file
and then write after machineKey
<httpCookies domain=".yourdomainname.com" />
I am creating user session using HttpContext from a function.
HttpContext cu;
string username = cu.User.Identity.Name;
username = Guid.NewGuid().ToString();
cu.Session["username"] = username;
HttpCookie hc = new HttpCookie("username", username);
hc.Domain = ".yourdomain.com";
hc.Expires = DateTime.Now.AddDays(1d);
cu.Response.Cookies.Add(hc);
With this code, I am able to share session within 3 sub-domains.
An application I'm modifying has a Web Service, and one of the web methods on that web methods is used to authenticate a user against active directory. So the current code called by the AuthenticateUser web method looks something like this:
string domainAndUsername = aDomain + #"\\" + username;
string ldsPath = buildLdsPath(searchBase);
DirectoryEntry entry = new DirectoryEntry(ldsPath, domainAndUsername,
password);
try
{
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(sAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
// more code to validate the result, etc...
}
When I started looking at this code, the first thing that worried me is the arguments to the web method look like this:
[WebMethod]
public ResultObj AddRole(string roleToAdd, string username, string password)
{
// code that calls above Authentication fragment...
}
So the current web service is expecting a password string, presumably sent in the clear over the network as XML, when the request is made to the service.asmx page.
Has anyone dealt with this type of issue before? Are there alternative Active Directory authentication mechanisms I could use that would avoid having to pass in a plain-text password? The best option I could come up with on my own is to invoke the WebMethod using an encrypted password, and have the code on the other side decrypt it. However, I'd prefer a better solution--e.g.: is there some way to do search for a DirectoryEntry using a one-way hash instead of a password?
Edit:
Additional Details: To this point I haven't considered SSL as this is a tool that is internal to our company, so it seems like overkill, and possibly problematic (it'll be running on a company intranet, and not externally visible). The only reason I'm even worried about the security of sending plain-text passwords is the escalating amount of (possibly password-sniffing) malware present even on company intranets these days.
If you have a public/private key combination, then the client could encrypt with the public key, and you decrypt with the private key.
However, that's too much work for the client, and not a very "web method" way of doing it.
Since you are sending the user name and password as parameters then you should resort to transport security, HTTPS, basically, which requires you to have a public/private key combination issued to you from a trusted certificate authority.
It should be noted that your association of SSL encrypted channel with an external facing site is incorrect. The point of wanting to encrypt a channel is to prevent man-in-the-middle attacks, exactly like you are trying to do here.
You could use a self-issued certificate, but that would require installing the public key of the certificate on each machine that is going to call your web method. It's easier to just get one from a trusted authority.
HTTPS (as mentioned) is the easy choice. Or, you could just let IIS handle authentication thru Digest or NTLM. Your app can still make authorization rules. NTLM is secure, but it'll hurt your interop. Otherwise, AD does offer some digest authentication methods, but I don't have tested code using them.
With Server 2000 domains, there's an option for "Store passwords in reversible format" - that will allow a domain controller to calculate MD5 hashes of the password to compare against your presented MD5 hash. MS realized this was a bit of a security problem, though, so Server 2003 implemented "Advanced" digest authentication - which precomputes the hash.
LDAP signon should select MD5 Digest as the authentication type, supply the username, and then supply the MD5 hash of the password. The normal LDAP clients will probably want to MD5 your password themselves though, so you'll have to override or craft them yourself.
We put our AD service on its own web site and got an SSL cert. Problem solved.
I think SSL, or possibly IPSec, are probably your best solutions.
For our particular situation, because both the client and the web service are running on our company Intranet, a solution that may work for us is to handle the Authentication on the client end using the Integrated Windows NTLM authentication, and then then just have the client supply the credentials to the Web Service. Here is the client code:
public void AddRole(string roleName)
{
webSvc.Credentials = CredentialCache.DefaultCredentials;
// Invoke the WebMethod
webSvc.AddRole(roleName);
}
The web method will now look like this:
[WebMethod]
public ResultObj AddRole(string roleToAdd)
{
IIdentity identity = Thread.CurrentPrincipal.Identity;
if (!identity.IsAuthenticated)
{
throw new UnauthorizedAccessException(
ConfigurationManager.AppSettings["NotAuthorizedErrorMsg"]);
}
// Remaining code to add role....
}
Again, I must stress this solution will probably only work if the server trusts the client, and both talk to the same Active Directory server. For public Web Services, one of the other answers given is going to be a better solution.
For further information, see:
Microsoft Support Article on passing credentials
MSDN Article on Building Secure Applications
MSDN Article on Windows Authentication - includes info on correctly configuring the web service to use the Windows Principal and Identity objects needed.