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" />
    </credentials>
  </forms>
</authentication>

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!

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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