91

I have an ASP.NET MVC3 C# .NET Application running on IIS 7.5.

We have a Windows NT service account we Impersonate in our code in order to read/write documents to a file share. The user id is compiled in the code and the service account password is stored in the web.config file.

The password contains an ampersand character (i.e.: p&ssword).

This broke the site. When accessing the site we received this error :"Sorry, an error occurred while processing your request".

Here is the code that uses the password:

    var password = ConfigurationManager.AppSettings.Get(Common.SVC_PWD);

    bool isSuccess = LogonUser(
        @"my_svc_acct",
        "my.domain.net",
        password,
        LOGON32_LOGON_NEW_CREDENTIALS,
        LOGON32_PROVIDER_DEFAULT, ref token
    );

Why would this cause the site to break?

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
MikeTWebb
  • 9,149
  • 25
  • 93
  • 132
  • 5
    I think because web.config is treated as an XML document - see here http://stackoverflow.com/questions/3824351/how-to-include-ampersand-in-connection-string-password-when-using-entity-framewo – Scott Selby Jan 30 '13 at 15:45
  • 2
    My first guess is that the password in the config file is incorrect. But have you tried calling GetLastError (http://msdn.microsoft.com/en-us/library/windows/desktop/ms679360(v=vs.85).aspx) to see what the error is? I also have to add that storing a clear-text password in a configuration file is not a good idea; I'd encrypt it at a minimum. – Jeff Siver Jan 30 '13 at 15:48

3 Answers3

172

I suspect that you didn't encode the password properly in the web.config file. Remember that web.config is a XML file, so entities must be encoded.

Instead of

my&password 

try

my&password

You can use sites such as FreeFormatter.com to escape/unescape XML strings.

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
  • 3
    everyone how use it for URL be careful! URL with "&" is NOT the URL with "&". Don't forget to replace it by code before applying it for your URL address. I have fallen into this pitfall and dealt with a bug for whole day before finding the reason. – Mr.B Nov 28 '17 at 12:10
64

You will need to put the encoded value in the web.config. It will read it out properly once you pull it but in the config file itself it needs to be encoded.

eg:

Password: your&password (what you expect)

Encoded version: your&password (what should be stored in your web.config)

Your wrapper method that reads out the value should unencode it automatically to your&password.

You will need to do this for all 'special' characters:

< = &lt;
> = &gt;
" = &quot;
' = &apos;
& = &amp;
Kelsey
  • 47,246
  • 16
  • 124
  • 162
-1

store the password in the web.config using CDATA

replace the password with this

<![CDATA[MyPassw&rd]]>
Scott Selby
  • 9,420
  • 12
  • 57
  • 96