24

I built a small website and there will be only one admin, so in the admin panel I am asking for a password with a value that I do not retrieve from a database, I just hard coded it in the function in code behind, I know this is wrong though I don't know why.

So is hard coding it in web.config the right thing to do? and how?

Maen
  • 1,030
  • 7
  • 19
  • 33

2 Answers2

57

As far as it being wrong... the problem is that if you ever need to change it, and it's hardcoded in your codebehind, you need to recompile,republish, re-deploy your website, whereas a change to the web.config can be done without doing this.

You could put it in an AppSetting in the web.config like so.

<appSettings>
   <add key="AdminPassword" value="ASDF1234" />
</appSettings>

and use this code to retrieve it

System.Configuration.ConfigurationManager.AppSettings["AdminPassword"].ToString()

Though I'd have a look at this.

https://web.archive.org/web/20211029043331/https://aspnet.4guysfromrolla.com/articles/021506-1.aspx

It covers encrypting sections of your web.config

Eoin Campbell
  • 43,500
  • 17
  • 101
  • 157
  • Do you have to restart the web server (IIS) in order for the **web.config** to take effect? Is there a better way? – TheTechGuy Oct 03 '13 at 14:40
  • seems like the solution, but why would I get the ol' "Cannot resolve symbol ToString?" – whyoz Dec 16 '14 at 19:09
  • 6
    I know this is really old but... but the syntax should be: `System.Configuration.ConfigurationManager.AppSettings("AdminPassword").ToString()` – Jeroen Mar 01 '16 at 00:15
  • 2
    You put a c# syntax AppSettings["AdminPassword"] Should be AppSettings("AdminPassword") – tapatio Sep 22 '17 at 15:16
  • I think this syntax for VS 2015 is actually `System.Configuration.ConfigurationManager.AppSettings.GetValues("AdminPassword").ToString()` – Arvo Bowen Jul 18 '18 at 23:19
3

Nothing wrong with Eoin's suggestion for tiny projects but if your project may someday need more than 1 admin and different types of users roles. I would take the hit and setup ASP membership.

http://msdn.microsoft.com/en-us/library/ms998347.aspx

You can use integrate it into windows or use a database and it's not too hard to setup. Especially if you use the built in config tool in IIS.

Chad Grant
  • 44,326
  • 9
  • 65
  • 80
  • yep. absolutely agreed. it's envariably worth taking the hit as well cos you just know you'll have to do it sooner or later. – Eoin Campbell Sep 12 '12 at 10:52