6

I have a strange problem on my login page in Asp.net this problem only happens with Safari.

When the user is validated I fetch the name of the user from the database (the field in the database is UTF8) and save it in a cookie. The problem is that when the user has a name with special characters I get redirected to the page where I came from without being logged in. For example "Moller" works fine and the user is logged in but not "Møller".

Again this is only happening with Safari and when I have special characters in the name. The row that isn't working is: Response.Cookies["userInfo"]["name"] = getNameFromUserid(userid);

This is my code:

string userid = validUserWithEmail(TextBoxEmail.Text, TextBoxPassword.Text);
if (userid != null) {
    //VALID USER
    Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(30);
    Response.Cookies["userInfo"]["name"] = getNameFromUserid(userid);

    FormsAuthentication.RedirectFromLoginPage(userid, CheckBoxPersistCookie.Checked);
} 
else
{
    //NOT A VALID USER SHOW A MESSAGE FOR THE USER OR SOMETHING
}
Martin
  • 7,190
  • 9
  • 40
  • 48
  • Is the safari a Windows or Mac / iOS version? I have same issue with my asp.net application, but only on Mac version of Safari. – Adrian Salazar Jul 19 '12 at 18:03

1 Answers1

7

Safari will not set cookies with non-ASCII characters in their value and other browsers can be unpredictable in how they display non-ASCII characters. As semi-colon is also not allowed in cookie values for any browser I would recommend using UrlEncode/UrlDecode.

If you are just writing the cookie and do not have control over the site reading/displaying the value to put in the URLDecode you can also do something like this:

ckCookie.Value = (Server.HtmlEncode( strSpecialCharacters )).Replace(";","");

This will ensure the full string is set in the cookie and Safari, Chrome, Firefox and IE will still recognize the html codes even without the ; and does not require decoding when read.

For a longer answer on cookie specs see: Allowed characters in cookies

Community
  • 1
  • 1
Luke
  • 156
  • 5
  • Thanks for explaining! But the problem is now instead that I get a asp.net error message "A potentially dangerous Request.Cookies value was detected from the client" when for example trying to use "Müller" in my cookie that is encoded to: "Mü". How can I solve this issue? – Martin Jun 02 '11 at 16:50
  • 4
    The solution seems to be to use UrlEncode instead: http://madskristensen.net/post/Cookies-and-Unicode-characters.aspx – Martin Jun 02 '11 at 17:02
  • 1
    @Martin the page you mentioned in your comment, doesn't contain expected content now :( I highly recommend to create an answer with content here at SO in such cases. this is because most of the links go down or change over time – Zeeshan Nov 27 '15 at 11:02