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:

Configuration webconfig = WebConfigurationManager.OpenWebConfiguration("~");

SystemWebSectionGroup sysweb = (SystemWebSectionGroup)webconfig.GetSectionGroup("system.web");

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 User

user.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).

Published Tuesday, November 18, 2008 2:19 PM by guru_sarkar

Comments

# re: Changing user password in Web.config

Tuesday, November 18, 2008 11:07 PM by Joe Chung

Bad practice to give the Windows account running your ASP.NET application write privileges to Web.config.

Bad practice to store credentials (any, let alone admin) as cleartext in Web.config.

# re: Changing user password in Web.config

Wednesday, November 19, 2008 2:03 PM by guru_sarkar

Joe Chung ...

Correct ... it is a bad practice.

One should use it only when absolutly necessary.

# re: Changing user password in Web.config

Tuesday, March 10, 2009 2:52 AM by Jun

Hi -

Did you encounter an error when your password contains special characters like & or \ or / or % or *.

# re: Changing user password in Web.config

Wednesday, March 11, 2009 11:31 AM by guru_sarkar

Jun:

I did not try that sort of password. Will get back if I find something.

What is the error that you are getting?

# re: Changing user password in Web.config

Thursday, May 21, 2009 7:28 AM by bedanand

This is good feature to be able to put user credentials on web.config if you have fixed/small users looging in your site. basicaly admin users.

Leave a Comment

(required) 
(required) 
(optional)
(required)