Reading the web.config credentials with C#

If you have a section such as this in your ASP.NET web.config:

<authentication mode="Forms">
  <!-- 525600 mins = 1 year -->
  <forms cookieless="UseCookies" timeout="525600">
    <credentials passwordFormat="Clear">
      <user name="jdoe" password="jdoesPassword" />
      <user name="mrFancypants" password="fancyPassword" />

You can access the user credentials via C# with the following code

var webConfig = WebConfigurationManager.OpenWebConfiguration("~");
var authSection = (AuthenticationSection)webConfig.GetSection("system.web/authentication");
var user = authSection.Forms.Credentials.Users["jdoe"];

// Check if the user exists and if the passwords match
if (user == null || user.Password != "aPasswordHere")
    throw new ApplicationException(notAuthMessage);

I hope this will save you some time!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s