Changing user password in Web.config
Say you have your user credientials placed in your web.config . How do you change the passord for a user programatically. Less talk, more code.
Sample web.config in root folder:
system.web> <compilation debug="true" /> <authentication mode="Forms"><forms loginUrl="login.aspx" defaultUrl="default.aspx"><
<
credentials passwordFormat="Clear"><user name="user" password="user" /><
user name="admin" password="admin" /></credentials></
forms></authentication><
authorization><deny users="?"/> </authorization> </system.web>Code for changing Password:
webconfig = WebConfigurationManager.OpenWebConfiguration("~"); SystemWebSectionGroup sysweb = (SystemWebSectionGroup)webconfig.GetSectionGroup("system.web");Configuration
AuthenticationSection authSection = sysweb.Authentication;
FormsAuthenticationUserCollection users = authSection.Forms.Credentials.Users;
FormsAuthenticationUser user = users["UserName"]; //you can grab it from a textbox or User.Identity.Name ~ current LoggedIn Useruser.Password = "newPassword" //you can grab it from a textbox......
webconfig.Save();
Namespaces added:
using
System.Configuration;using
System.Web.Configuration;
Points to Note:
- Configuration webconfig = WebConfigurationManager.OpenWebConfiguration("~");
I got an exception : “System.InvalidOperationException: ConfigurationSection properties cannot be edited when locked” when tried to use Configuration webconfig = WebConfigurationManager.OpenWebConfiguration("~//web.config");
- Permissions to web.config
Make sure to grant Modify/Write permission to ASPNET useraccount (or the user account which is going to perform this action).