public HttpResponseMessage Login(User user) { var response = new HttpResponseMessage(); if (ModelState.IsValid) { if (setup.ValidateLogin(user)) { // --- stupid part starts here --- var context = Request.Properties["MS_HttpContext"] as System.Web.HttpContextWrapper; string useragent = context.Request.UserAgent; string ip = context.Request.UserHostAddress; Random rand = new Random(); Session session = new Session() { User = user, Authorised = true, IP = ip, UserAgent = useragent }; // here we'll generate some random color every time user logs in // for the random value of the cookie string color = String.Format("{0:X6}", rand.Next(0x1000000)); string secret = setup.GenerateSessionKey(session, color); response = new HttpResponseMessage(HttpStatusCode.OK); response.Headers.Location = new Uri(Request.RequestUri.Authority + "/profile/index/" + user.Username); if (secret != null) { System.Net.Http.Headers.CookieHeaderValue cookie = new System.Net.Http.Headers.CookieHeaderValue("filth.sid", secret); // in case of 'remember me' ... if (user.Remember) { cookie.Expires = DateTime.Now.AddMonths(12); } // some browsers (*IE) are sometimes strict about some exotic standards - // 'localhost' can't be the name for cookie's domain // more info at http://curl.haxx.se/rfc/cookie_spec.html if (!Request.RequestUri.Host.Contains("localhost")) { cookie.Domain = Request.RequestUri.Host; } cookie.Path = "/"; cookie.HttpOnly = true; // prevents JavaScript-based cookie theft response.Headers.AddCookies(new System.Net.Http.Headers.CookieHeaderValue[] { cookie }); } // --- stupid part ends here --- } else { response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, new Exception("Nope. Either you entered invalid combination or credentials doesn't exist.")); } } else { response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } return(response); }