So i remember that my teacher once taught us how to secure connectionstrings in web.config.
Unfortunately, now when i need to know it, i have forgotten all about it.
I have been looking around in here, and found some different questions regarding this, where all of which seemed to have a slightly complicated solution.
Im asking, because i remember that my teacher secured his password in the connectionstring with just a few signs/glyphs, instead of encrypting the entire string.
So my question is obviously how i can secure (doesn't have to be very strong) my connectionstring in one easy way.
you can try using flags in the connecction string as follows:
<add name="PSystem"
connectionString="Server=test;
Database=Dev;
User ID=#UserID#;
Password=#Password#;
Trusted_Connection=False;
Encrypt=True;"
providerName="System.Data.SqlClient" />
then you can have the encrypted user and password as follows:
<add key="DB_User" value = [Encrypted Username]>
<add key="DB_Password" value = [Encrypted Password]>
Then in code you just replace the flags:
string _connectionString = ConfigurationManager.ConnectionStrings["PSystem"].ConnectionString;
string user = Decrypt(ConfigurationManager.AppSettings["DB_User"]);
string password = Decrypt(ConfigurationManager.AppSettings["DB_Password"]);
_connectionString = _connectionString.Replace("##User##", user).Replace("##Password##", password);
For all above, thanks to Oscar Rivera answer as well. Hope this helps!
Related
I am trying to update just the 'Comments' property in ASP. NET MembershipUser and want to leave all other property untouched. Here is my codes
MembershipUser userComments = Membership.GetUser(sUserName);
userComments.Comment = "Need Change Password";
Membership.UpdateUser(userComments);
It throws an expection 'The E-mail supplied already exists in the database for the application' at Membership.UpdateUser(userComments)
How can I just update only the 'Comments' without changing emails or any other properties?
Based on your comment, it is throwing configuration exception. You can ignore this validation by setting requiresUniqueEmail to false in your web.config.
<add name="AspNetSqlMembershipProvider"
....
requiresUniqueEmail="false"
....
/>
However it is possible that you have a duplicate email in your database and the framework doesn't know for which one you're trying to update Comment. So to get rid of the duplicate might be a better option.
I have several connection strings defined in web.config, e.g.
<add
name="exampleConnStr"
connectionString="Driver=ODBCDriver;server=blah;"
providerName="Systerm.Data.Odbc"
/>
I'm drowning in MSDN documentation (which doesn't seem very good quality if I'm honest). What I'm trying to do is execute the same query against all of the databases defined within the web.config from an ASP page.
Can anyone show an example or provide search criteria likely to give me a hint?
Thanks
From what I can tell this is a very straight forward task. You will need to use the System.Configuration namespace for this.
using System.Configuration;
string conString;
for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
{
conString = ConfigurationManager.ConnectionStrings[i].ConnectionString;
// No point to the conString variable, just showing how to access the connectionstring.
}
I'm finding surprisingly little information on converting an existing database from Encrypted passwords to Hashed passwords. (I was able to find a bit more information on converting the other way, but it wasn't of much help.)
As most people know, changing the passwordFormat setting in web.config only affects new users. I have a database with a couple of hundred users and I'd like to convert them to use hashed passwords without changing those existing passwords.
Is anyone else familiar with how one might approach this? Thanks for any tips.
Greg's solution is a good start, but it won't affect existing users. The SqlMembershipProvider protects existing users and passwords by storing the PasswordFormat (0=clear, 1=Hashed, 2=Encrypted) in the table along with passwords. Changing the provider password format only affects inserts to the user tables. In order to convert existing users' passwords to Hashed, you have to change the PasswordFormat parameter for each entry. Here is a simple way to do this:
void HashAllPasswords()
{
var clearProvider = Membership.Providers["SqlProvider_Clear"];
var hashedProvider = Membership.Providers["SqlProvider_Hashed"];
int dontCare;
if (clearProvider == null || hashedProvider == null) return;
var passwords = clearProvider.GetAllUsers(0, int.MaxValue, out dontCare)
.Cast<MembershipUser>().ToDictionary(u => u.UserName, u => u.GetPassword());
using (var conn = new SqlConnection(
ConfigurationManager.ConnectionStrings[0].ConnectionString))
{
conn.Open();
using (var cmd = new SqlCommand(
"UPDATE [aspnet_Membership] SET [PasswordFormat]=1", conn))
cmd.ExecuteNonQuery();
}
foreach (var entry in passwords)
{
var resetPassword = hashedProvider.ResetPassword(entry.Key, null);
hashedProvider.ChangePassword(entry.Key, resetPassword, entry.Value);
}
}
This is the approach I'd start with to see how far I got:
Create two MembershipProviders in my web.config, one for encrypted passwords and one for hashed.
Loop through all users using encrypted password provider. (SqlMembershipProvider.GetAllUsers)
Get the user's password using encrypted password provider. (MembershipUser.GetPassword)
Change the user's password to the same password using hashed password provider. (MembershipUser.ChangePassword)
So it'd be something like this:
<membership defaultProvider="HashedProvider">
<providers>
<clear />
<add name="HashedProvider" connectionStringName="MembershipConnectionString" enablePasswordRetrieval="false" requiresQuestionAndAnswer="false" applicationName="MyApp" passwordFormat="Hashed" type="System.Web.Security.SqlMembershipProvider" />
<add name="EncryptedProvider" connectionStringName="MembershipConnectionString" enablePasswordRetrieval="true" requiresQuestionAndAnswer="false" applicationName="MyApp" passwordFormat="Encrypted" type="System.Web.Security.SqlMembershipProvider" />
</providers>
</membership>
code:
SqlMembershipProvider hashedProvider = (SqlMembershipProvider)Membership.Providers["HashedProvider"];
SqlMembershipProvider encryptedProvider = (SqlMembershipProvider)Membership.Providers["EncryptedProvider"];
int unimportant;
foreach (MembershipUser user in encryptedProvider.GetAllUsers(0, Int32.MaxValue, out unimportant ))
{
hashedProvider.ChangePassword(user.UserName, user.GetPassword(), user.GetPassword());
}
For security reasons, it's definitely the right decision to switch from encrypted passwords to hashes in your database.
Encryption vs Hashing
Generally to create hashes out of your existing encrypted passwords, you should first decrypt them and then hash them. Be aware that you will loose (when you finally switch) the original passwords. Instead you're going to have a unique fingerprint (hash) of the users passwords.
Think also about using salt for the hashing (defense against rainbow tables etc.) and also have a look in slow hashing algorithms like BCrypt (Codeplex & Article: How To Safely Store A Password) for security reasons instead of fast ones like MD5.
Keep also in mind, that it will be way more effort to switch the hashing algorithm in the future than changing it from ecryption to hash. So you want to do it right the first time ;)
I would caution you against hashing your passwords haphazardly since there are a lot of caveats to that approach. This Blog post about hashing passwords was very insightful to me, and I think that you should read it. Why do you want hashed passwords instead of encrypted?
so I'm very very far from an expert on MVC or ASP.NET. I just want to make a few simple Controllers in C# at the moment, so I have the following question;
Right now I have the connection string used by the controller, -inside- the controller itself. Which is kind of silly when there are multiple controllers using the same string. I'd like to be able to change the connection string in just one place and have it affect all controllers.
Not knowing a lot about asp.net or the 'm' and 'v' part of MVC, what would be the best (and simplest) way of going about accomplishing just this?
I'd appreciate any input on this, examples would be great too.
Put it in your web.config file like so:
<connectionStrings>
<add name="ConnectionName" connectionString="TheConnectionString" providerName="System.Data.SqlClient" />
</connectionStrings>
<connectionStrings> is just a child of the root <configuration> element.
Then you can read it like:
string myConnStr = ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
HTHs,
Charles
You may add a connection string to the web.config file like this:
<configuration>
<appSettings>
<add key="ConnectionString"
value="server=localhost;database=Northwind;uid=sa;password=secret;"/>
</appSettings>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
and use it in your code like this:
strConnection = ConfigurationSettings.AppSettings("ConnectionString") // <-----
sqlConn = New SqlConnection(strConnection)
sqlCmd = New SqlCommand("SELECT * FROM Customers WHERE " & "(CompanyName LIKE 'A%') OR (CompanyName LIKE 'B%')", sqlConn)
Notice the first line. This example is for VB but you should be able to do the same in C#.
The example is taken from this link http://www.dotnetjohn.com/articles.aspx?articleid=3, but there are tons of them everywhere.
Hope this helps.
I have an C# asp.net app using the default Sql MembershipProvider. My web.config has a few settings that control how I'm using this Provider:
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresUniqueEmail="true"
passwordFormat="Hashed"
minRequiredPasswordLength="5"
The problem I'm running into is that when people reset their passwords, it seems the ResetPassword() method returns a password that is longer than I want and has characters that can be confusing (l,1,i,I,0,O). Furthermore, I'm sending my users an email with a plain-text message and an HTML message (I'm using MailMessage with AlternateViews). If the password has unsafe HTML characters in it, when the email clients render the HTML text the password might be different (e.g. the %, &, and < aren't exactly HTML safe).
I've looked over the "add" element that belongs in the web.config, but I don't see any extra configuration properties to only include certain characters in the ResetPassword() method and to limit the password length.
Can I configure the ResetPassword() method to limit the password length and limit the character set it is choosing from?
Right now I have a workaround: I call ResetPassword() to make sure the supplied answer is correct, and then I use a RandomPassword generator I downloaded off the internet to generate a password that I like (without ambiguous characters, HTML safe, and only 8 characters long) and then I call ChangePassword() to change the user's password after I've already reset it.
My workaround seems kludgy and I thought it would be better to configure ResetPassword() to do what I want.
Thank you~!
ColoradoTechie
I don't believe you can do anything to "configure" the ResetPassword() call. You could write your own provider that changes how the ResetPassword() works.
This link describes the same tactic you seem to be doing already....
Staying with your work around/hack may be the simplest way to go. :-)
However, if you want to learn more on how to create your own provider check out these links.
http://www.asp.net/learn/videos/video-189.aspx
http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx
http://www.devx.com/asp/Article/29256/0/page/3
http://www.15seconds.com/issue/050216.htm
Using the GeneratePassword method ensures at least that the created password fulfills your setup for MinRequiredPasswordLength and MinRequiredNonAlphanumericCharacters. I am doing something like this:
// aUser is of class MembershipUser
string aTempPassword = aUser.ResetPassword();
string aNewPassword = Membership.GeneratePassword(
Membership.MinRequiredPasswordLength,
Membership.MinRequiredNonAlphanumericCharacters);
aUser.ChangePassword(aTempPassword, aNewPassword);
Well, that's only 50% of what you want since you cannot control the character set used for the final password.
(Actually that's also from my viewpoint the more important aspect - especially if you have users who need 10 minutes and 3 support calls to hit the key combination of a curled bracket successfully and don't have a clue what a clipboard is. ResetPassword can make you one of the most hated persons.)
I know this has already been answered but I wanted to add my 2 cents since I came across this issue today.
The SQLMembershipProvider class exposes
public virtual string GeneratePassword()
which is called by ResetPassword. Therefore you can simply extend the SQLMembershipProvider class and implement your own version of GeneratePassword.
Note that doing so will require you to update the membership provider entry in your web.config to use your new membership provider class:
<membership>
<providers>
<add type="My.Namespace.MyCustomSqlMembershipProvider" ... />