protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) {

      if (HttpContext.Current.User.Identity.IsAuthenticated) {
        return await base.SendAsync(request, cancellationToken);
      }
      if (!CanHandleAuthentication(request)) {
        return await base.SendAsync(request, cancellationToken);
      }
      bool isAuthenticated;
      try {
        isAuthenticated = Authenticate(request);
      }
      catch (Exception) {
        return CreateUnauthorizedResponse();
      }
      if (isAuthenticated) {
        var response = await base.SendAsync(request, cancellationToken);

        // add token cookie value
        IEnumerable<CookieHeaderValue> ccoll = new CookieHeaderValue[] { new CookieHeaderValue(_TokenName, _Token) };
        response.Headers.AddCookies(ccoll);
        
        return response.StatusCode == HttpStatusCode.Unauthorized ? CreateUnauthorizedResponse() : response;
      }
      return CreateUnauthorizedResponse();
    }
Example #2
0
        public static IEnumerable<HttpCookie> CookiesFor(CookieHeaderValue value)
        {
            return value.Cookies.Select(x =>
            {
                var cookie = new HttpCookie(x.Name)
                {
                    Path = value.Path,
                    Domain = value.Domain,
                    HttpOnly = value.HttpOnly,
                    Secure = value.Secure
                };

                if (value.Expires.HasValue)
                {
                    cookie.Expires = value.Expires.Value.UtcDateTime;
                }

                if (x.Values.Count == 1)
                {
                    cookie.Value = x.Values.ToString();
                    return cookie;
                }

                x.Values
                    .AllKeys
                    .Each(key =>
                          {
                              cookie.Values[key] = x.Values[key];
                          });

                return cookie;
            });
        }
        public async Task<HttpResponseMessage> Authenticate([FromBody]AuthenticationRequest authReq)
        {
            try
            {
                if (authReq == null)
                    return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No Credentials");

                if (!ModelState.IsValid)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid Credentials");
                }

                User possibleUser = await repo.Authenticate(authReq);

                if (possibleUser == null)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid Credentials");
                }
                
                HttpResponseMessage retVal = Request.CreateResponse<User>(HttpStatusCode.OK, possibleUser);
                retVal.Headers.Add("OGVSession", possibleUser.SessionGuid);
                CookieHeaderValue cookie = new CookieHeaderValue("OGVSession", possibleUser.UserName);
                
                retVal.Headers.AddCookies(new List<CookieHeaderValue>() { cookie });
                return retVal;
            }
            catch (Exception ex)
            {

                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.ToString());
            }

        }
 public static void SetSerializedCookieValue(this HttpResponseMessage response, string key, string value)
 {
     if (response != null) {
         var cookieValue = new CookieHeaderValue(key, value);
         response.Headers.AddCookies(new CookieHeaderValue[] {cookieValue});
     }
 }
Example #5
0
        public HttpResponseMessage AddToCart([FromBody]int productId)
        {
            UnitOfWork.BeginTransaction();
            var cart = GetCartInternal();
            var response = Request.CreateResponse();
            if (cart == null)
            {
                cart = new Cart();
                cart.Id = Guid.NewGuid();
                var serverCookie = new CookieHeaderValue("cart_guid", cart.Id.ToString() );
                response.Headers.AddCookies(new CookieHeaderValue[] { serverCookie });
            }
            var product = Repository.GetProduct(productId);
            var lineItem = cart.LineItems.FirstOrDefault(x => x.Product.Id == productId);

            if(lineItem==null)
            {
                lineItem = new LineItem { Price = product.Price, Product = product };
                cart.LineItems.Add(lineItem);
            }

            lineItem.Quantity++;
            lineItem.Price = product.Price;
            Repository.SaveCart(cart);
            UnitOfWork.Commit();
            return response;
        }
        public override void OnActionExecuted(HttpActionExecutedContext context)
        {
            if (context.Response == null) return;

            //don't need to set the cookie if they already exist
            if (context.Request.Headers.GetCookies(AngularAntiForgeryHelper.AngularCookieName).Any()
                && context.Request.Headers.GetCookies(AngularAntiForgeryHelper.CsrfValidationCookieName).Any())
            {
                return;
            }

            string cookieToken, headerToken;
            AngularAntiForgeryHelper.GetTokens(out cookieToken, out headerToken);

            //We need to set 2 cookies: one is the cookie value that angular will use to set a header value on each request,
            // the 2nd is the validation value generated by the anti-forgery helper that we use to validate the header token against.

            var angularCookie = new CookieHeaderValue(AngularAntiForgeryHelper.AngularCookieName, headerToken)
                {
                    Path = "/",
                    //must be js readable
                    HttpOnly = false,
                    Secure = GlobalSettings.UseSSL
                };

            var validationCookie = new CookieHeaderValue(AngularAntiForgeryHelper.CsrfValidationCookieName, cookieToken)
            {
                Path = "/",
                HttpOnly = true,
                Secure = GlobalSettings.UseSSL
            };

            context.Response.Headers.AddCookies(new[] { angularCookie, validationCookie });
        }
        public HttpResponseMessage CreateAccount(LogonRequestModel logonModel)
        {
            if (ModelState.IsValid)
            {
                var driverId = _driverRepository.CreateDriver(logonModel.Email, logonModel.Password);
                if (driverId > 0)
                {
                    var driver = _driverRepository.GetDriverById(driverId);
                    if (driver.Token == null)
                    {
                        driver.Token = new AccessToken();
                    }
                    AccountHelper.SetToken(driver.Token, driverId);
                    _driverRepository.UpdateDriver(driver);
                    var responseMessage = Request.CreateResponse<LogonResponseModel>(HttpStatusCode.OK, AccountHelper.GetLogonResponseModel(true, driver.Token.Token, driver.DriverId, driver.EmailAddress));
                    SecurityHelper.SetUseronThread(driver);

                    var cookie = new CookieHeaderValue(SecurityHelper.AccessTokenCookieName, driver.Token.Token);
                    cookie.Expires = DateTimeOffset.Now.AddDays(14);
                    cookie.Path = "/";

                    responseMessage.Headers.AddCookies(new CookieHeaderValue[] { cookie });

                    return responseMessage;
                }
                else
                {
                    return Request.CreateResponse<LogonResponseModel>(HttpStatusCode.OK, AccountHelper.GetLogonResponseModel(false));
                }
            }

            return Request.CreateResponse<LogonResponseModel>(HttpStatusCode.BadRequest, AccountHelper.GetLogonResponseModel(false));
        }
        public async Task<HttpResponseMessage> ProcessCallback()
        {
            var requestParams = Request.GetQueryNameValuePairs();
            var oauthToken = requestParams.Where(p => p.Key.Equals(TwitterOauthUtils.OAuthTokenKey)).FirstOrDefault();
            var oauthTokenVerifier = requestParams.Where(p => p.Key.Equals(TwitterOauthUtils.OAuthVerifierKey)).FirstOrDefault();


            // exchange the oauth token and oauth token verifier for a user access token
            var userAccessInfo = await AccessTokenExchange(oauthToken.Value, oauthTokenVerifier.Value);


            // compute a user access cookie and send the user back to the home page.
            var cookieValue = TwitterOauthUtils.ConstructUserAccessCookieValue(userAccessInfo);
            UserAuthInfo userAuthInfo;
            UserInfo userInfo;
            TwitterOauthUtils.ParseUserAccessCookie(cookieValue, out userInfo, out userAuthInfo);
            Program.SetUserAuthInfo(userAuthInfo);

            CookieHeaderValue userAccessCookie = new CookieHeaderValue(UserAccessCookieName, cookieValue);
            userAccessCookie.Path = "/";

            var response = Request.CreateResponse(HttpStatusCode.Moved);
            response.Headers.AddCookies(new CookieHeaderValue[] { userAccessCookie });
            response.Headers.Location = new System.Uri(AppHomeRoute);

            return response;
        }
 public void CookieHeaderValue_Ctor1_InitializesCorrectly()
 {
     CookieHeaderValue header = new CookieHeaderValue("cookie", "value");
     Assert.Equal(1, header.Cookies.Count);
     Assert.Equal("cookie", header.Cookies[0].Name);
     Assert.Equal("value", header.Cookies[0].Values.AllKeys[0]);
 }
Example #10
0
        public static void SetAuthCookie(this HttpResponseMessage response, string login)
        {
            if (login == null)
            {
                var authCookie = new CookieHeaderValue(System.Web.Security.FormsAuthentication.FormsCookieName, "");

                authCookie.Expires = DateTime.UtcNow.AddDays(-1);
                authCookie.HttpOnly = true;

                response.Headers.AddCookies(new[] { authCookie });
            }
            else
            {

                var authTicket = new System.Web.Security.FormsAuthenticationTicket
                  (
                     1, //version
                     login, // user name
                     DateTime.Now,             //creation
                     DateTime.Now.AddYears(50), //Expiration (you can set it to 1 month
                     true,  //Persistent
                     login
                  ); // additional informations
                var encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(authTicket);

                var authCookie = new CookieHeaderValue(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket);

                authCookie.Expires = authTicket.Expiration;
                authCookie.HttpOnly = true;

                response.Headers.AddCookies(new[] { authCookie });
            }
        }
Example #11
0
        public static string DetermineName(CookieHeaderValue value)
        {
            var state = value.Cookies.SingleOrDefault();
            if(state == null) throw new ArgumentException("Must contain at least one CookieState", "value");

            return state.Name;
        }
        public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext == null) {
                throw new ArgumentNullException("actionContext");
            }

            string cookieToken, newCookieToken, headerToken;

            string tokenKey = AntiForgeryConfig.CookieName;

            CookieHeaderValue cookie = actionExecutedContext.Request.Headers.GetCookies(tokenKey).FirstOrDefault();
            cookieToken = cookie != null ? cookie[tokenKey].Value : null;

            AntiForgery.GetTokens(cookieToken, out newCookieToken, out headerToken);
            if (newCookieToken != null) {
                var newCookie = new CookieHeaderValue(tokenKey, newCookieToken);
                newCookie.HttpOnly = true;
                if (AntiForgeryConfig.RequireSsl) {
                    newCookie.Secure = true;
                }
                actionExecutedContext.Response.Headers.AddCookies( new CookieHeaderValue[] { newCookie });
            }

            actionExecutedContext.Response.Headers.Add(tokenKey, headerToken);

            return;
        }
        private HackathonWebApi.Membership.User SetupFormsAuthTicket(string userName, bool persistanceFlag)
        {
            var usersContext = new UsersContext();
            HackathonWebApi.Membership.User user = usersContext.GetUser(userName);
            var userId = user.UserId;
            var userData = userId.ToString(CultureInfo.InvariantCulture);
            var authTicket = new FormsAuthenticationTicket(1, //version
                                userName, // user name
                                DateTime.Now,             //creation
                                DateTime.Now.AddMinutes(30), //Expiration
                                persistanceFlag, //Persistent
                                userData);

            var encTicket = FormsAuthentication.Encrypt(authTicket);
            var response = Request.CreateResponse(HttpStatusCode.Created);

            //var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

            //var cookieHeaderValue = new CookieHeaderValue("loginCookie",);

            var cookie = new CookieHeaderValue("session-id", "12345");
            cookie.Cookies.Add(new CookieState(FormsAuthentication.FormsCookieName, encTicket));
            cookie.Expires = DateTimeOffset.Now.AddDays(1);
            cookie.Domain = Request.RequestUri.Host;
            cookie.Path = "/";

            response.Headers.AddCookies(new List<CookieHeaderValue> { cookie });
            return user;
        }
Example #14
0
 public static void ClearCookie(this HttpResponseHeaders self, string name, string path)
 {
     CookieHeaderValue cookie = new CookieHeaderValue(name, String.Empty)
     {
         Expires = DateTimeOffset.MinValue,
         Path = path,
         HttpOnly = true
     };
     self.AddCookies(new[] { cookie });
 }
 internal static CookieHeaderValue CreateAuthenticationCookie(UserModel model, string cookieDomain)
 {
     var sessionToken = AuthorizationHelper.CreateSessionToken(model);
     SessionTokenManager.Instance.Tokens.Add(sessionToken, model);
     var cookie = new CookieHeaderValue(Strings.SessionTokenName, sessionToken);
     cookie.Expires = DateTimeOffset.Now.AddDays(1);
     cookie.Domain = cookieDomain;
     cookie.Path = "/";
     return cookie;
 }
 public void CookieHeaderValue_Ctor2_InitializesCorrectly()
 {
     NameValueCollection nvc = new NameValueCollection();
     nvc.Add("name", "value");
     CookieHeaderValue header = new CookieHeaderValue("cookie", nvc);
     Assert.Equal(1, header.Cookies.Count);
     Assert.Equal("cookie", header.Cookies[0].Name);
     Assert.Equal("name", header.Cookies[0].Values.AllKeys[0]);
     Assert.Equal("value", header.Cookies[0].Values["name"]);
 }
        public void AuthenticationMessageHandler_ShouldSetNonAuthIdentity()
        {
            var context = GetContext();
            var messageHandler = new AuthenticationMessageHandler(context);

            var cookie = new CookieHeaderValue("task-manager-token", "11111111-8B86-D011-B42D-00CF4FC964FF");
            messageHandler.Authenticate(cookie);

            Assert.IsFalse(Thread.CurrentPrincipal.Identity.IsAuthenticated);
        }
        //----< GET api/File?fileName=foobar.txt&open=true >---------------
        //----< attempt to open or close FileStream >----------------------
        public HttpResponseMessage Get(string fileName, string open)
        {
            string sessionId;
              var response = new HttpResponseMessage();
              Models.Session session = new Models.Session();

              CookieHeaderValue cookie = Request.Headers.GetCookies("session-id").FirstOrDefault();
              if (cookie == null)
              {
            sessionId = session.incrSessionId();
            cookie = new CookieHeaderValue("session-id", sessionId);
            cookie.Expires = DateTimeOffset.Now.AddDays(1);
            cookie.Domain = Request.RequestUri.Host;
            cookie.Path = "/";
              }
              else
              {
            sessionId = cookie["session-id"].Value;
              }
              try
              {
            FileStream fs;
            string path = System.Web.HttpContext.Current.Server.MapPath("~\\App_Data\\");
            if (open == "download")  // attempt to open requested fileName
            {
              path = path + "DownLoad";
              string currentFileSpec = path + "\\" + fileName;
              fs = new FileStream(currentFileSpec, FileMode.Open);
              session.saveStream(fs, sessionId);
            }
            else if(open == "upload")
            {
              path = path + "UpLoad";
              string currentFileSpec = path + "\\" + fileName;
              fs = new FileStream(currentFileSpec, FileMode.OpenOrCreate);
              session.saveStream(fs, sessionId);
            }
            else  // close FileStream
            {
              fs = session.getStream(sessionId);
              session.removeStream(sessionId);
              fs.Close();
            }
            response.StatusCode = (HttpStatusCode)200;
              }
              catch
              {
            response.StatusCode = (HttpStatusCode)400;
              }
              finally  // return cookie to save current sessionId
              {
            response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
              }
              return response;
        }
        public HttpResponseMessage SetCookie()
        {
            CookieHeaderValue serverCookie = new CookieHeaderValue("server_cookie", "hello from server");
            serverCookie.Expires = DateTimeOffset.Now.AddDays(2);
            serverCookie.Domain = Request.RequestUri.Host;
            serverCookie.Path = "/";

            HttpResponseMessage response = Request.CreateResponse("This is response from the Web API.");

            response.Headers.AddCookies(new CookieHeaderValue[] { serverCookie });
            return response;
        }
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var currentUser = HttpContext.Current.User as UserDataPrincipal;
            if (currentUser != null && actionExecutedContext.Response != null)
            {
                var authCookie = currentUser.CreateAuthCookie();
                var cookieHeaderValue = new CookieHeaderValue(authCookie.Name, authCookie.Value);
                actionExecutedContext.Response.Headers.AddCookies(new[] { cookieHeaderValue });
            }

            base.OnActionExecuted(actionExecutedContext);
        }
Example #21
0
 public static void SetAuthCookie(this HttpResponseHeaders self, string token, string path, DateTimeOffset? expires)
 {
     CookieHeaderValue cookie = new CookieHeaderValue(ReviewRApiController.CookieName, token)
     {
         HttpOnly = true,
         Path = path
     };
     if (expires.HasValue)
     {
         cookie.Expires = expires.Value;
     }
     self.AddCookies(new[] { cookie });
 }
 public static void SetAccessToken(this HttpResponseMessage response, HttpRequestMessage request, string accessToken)
 {
     if (request.Headers.GetCookies(AuthenticateAttribute.CookieName).Any())
     {
     return;
     }
     CookieHeaderValue cookie = new CookieHeaderValue(AuthenticateAttribute.CookieName, accessToken)
     {
     HttpOnly = true,
     Path = "/"
     };
     response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
 }
Example #23
0
 public CookieHeaderValue GetCookieTicket(string content)
 {
     var cookie = new CookieTicket(content);
     CookieHeaderValue cookieValue = new CookieHeaderValue(CookieTicketConfig.CookieName, "Just Mock");
     cookieValue.HttpOnly = true;
     cookieValue.Secure = CookieTicketConfig.RequireSSL;
     cookieValue.Path = "/";
     if (cookie.Persistent)
     {
         cookieValue.Expires = cookie.IssueDate + CookieTicketConfig.Timeout;
     }
     return cookieValue;
 }
        public void AMH_ShouldSetRightIdentity()
        {
            var context = GetContext();
            var messageHandler = new AuthenticationMessageHandler(context);

            var cookie = new CookieHeaderValue("task-manager-token", "6F9619FF-8B86-D011-B42D-00CF4FC964FF");
            messageHandler.Authenticate(cookie);

            Assert.IsTrue(Thread.CurrentPrincipal.Identity.IsAuthenticated);
            Assert.AreEqual(Thread.CurrentPrincipal.Identity.Name, "ivan");
            Assert.IsTrue(Thread.CurrentPrincipal.IsInRole("role1"));
            Assert.IsFalse(Thread.CurrentPrincipal.IsInRole("role2"));
        }
Example #25
0
        public HttpResponseMessage GetSignOut()
        {
            var resp = new HttpResponseMessage();

            var cookie = new CookieHeaderValue(FormsAuthentication.FormsCookieName, "NoCookie")
            {
                Expires = new DateTime(1999, 10, 12),
            };

            resp.Headers.AddCookies(new[] { cookie });

            _userSigner.SignOff();
            return resp;
        }
Example #26
0
        //----< GET api/File?fileName=foobar.txt&open=true >---------------
        //----< attempt to open or close FileStream >----------------------

        public HttpResponseMessage Get(string fileName, string open)
        {
            string sessionId;
            var response = new HttpResponseMessage();
            Models.Session session = new Models.Session();
            CookieHeaderValue cookie = Request.Headers.GetCookies("session-id").FirstOrDefault();
            if (cookie == null) {
                sessionId = session.incrSessionId();
                cookie = new CookieHeaderValue("session-id", sessionId);
                cookie.Expires = DateTimeOffset.Now.AddDays(1);
                cookie.Domain = Request.RequestUri.Host;
                cookie.Path = "/";
            } else {
                sessionId = cookie["session-id"].Value;
            }
            try {
                FileStream fs;
                string path = System.Web.HttpContext.Current.Server.MapPath("~\\ZipFiles");
                if (open == "download") {
                    // attempt to open requested fileName
                    string currentFileSpec = path + "\\" + fileName;
                    fs = new FileStream(currentFileSpec, FileMode.Open);
                    session.saveStream(fs, sessionId);
                } else if (open == "upload") {
                    string path1 = System.Web.HttpContext.Current.Server.MapPath("~\\CollagePages\\UploadedFiles\\");
                    string a = Path.GetFileName(fileName);
                    string currentFileSpec = path1 + "\\" + a;
                    fs = new FileStream(currentFileSpec, FileMode.OpenOrCreate);
                    session.saveStream(fs, sessionId);
                } else {
                    // close FileStream 
                    fs = session.getStream(sessionId);
                    session.removeStream(sessionId);
                    fs.Close();
                    string storyXML = HttpContext.Current.Server.MapPath("~\\CollagePages\\UploadedFiles\\") + "story.xml";
                    if (System.IO.File.Exists(storyXML))
                        addStoryBlock(storyXML);
                }
                response.StatusCode = (HttpStatusCode)200;
            } catch {
                response.StatusCode = (HttpStatusCode)400;
            }
            finally {
                // return cookie to save current sessionId 
                response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
            }
            return response;
        }
        protected IHttpActionResult OkAuthorized(string username)
        {
            // not sure about this code
            HttpCookie cookie = FormsAuthentication.GetAuthCookie(username, false);

            var cookieHeaderValue = new CookieHeaderValue(cookie.Name, cookie.Value);
            cookieHeaderValue.Expires = cookie.Expires;
            cookieHeaderValue.Secure = cookie.Secure;
            cookieHeaderValue.HttpOnly = cookie.HttpOnly;
            cookieHeaderValue.Domain = cookie.Domain;
            cookieHeaderValue.Path = cookie.Path;

            var resp = new HttpResponseMessage();
            resp.Headers.AddCookies(new CookieHeaderValue[] { cookieHeaderValue });
            return new ResponseMessageResult(resp);
        }
        //Snippet 1
        public HttpResponseMessage Snippet1()
        {
            var resp = new HttpResponseMessage();

            System.Net.Http.Headers.CookieHeaderValue cookie = new System.Net.Http.Headers.CookieHeaderValue("CookieName11", "CookieVal11");
            CookieHeaderValue cookie1 = new CookieHeaderValue("CookieName12", "CookieVal12");

            cookie.Expires = DateTimeOffset.Now.AddDays(1);
            cookie.Path    = "/";
            // cookie.Secure = false;
            cookie.HttpOnly  = true;
            cookie1.Secure   = true;
            cookie1.HttpOnly = false;
            resp.Headers.AddCookies(new CookieHeaderValue[] { cookie, cookie1 });
            return(resp);
        }
        // POST: api/Login
        public async Task<HttpResponseMessage> Login([FromBody]ConnectionInfo info)
        {
            var connector = GetApiConnector(info);
            try
            {
                var loginInfo = await connector.LoginAsync(info.Username, info.Password);
                var message = new HttpResponseMessage(HttpStatusCode.OK);
                var sessionId = GetCookie(loginInfo.Cookie);
                var cookieSession = new CookieHeaderValue("workfront-session", sessionId);
                cookieSession.Expires = DateTimeOffset.Now.AddDays(1);
                //cookie.Domain = Request.RequestUri.Host;
                cookieSession.Path = "/";
                var cookieHost = new CookieHeaderValue("workfront-host", info.Host);
                cookieHost.Expires = DateTimeOffset.Now.AddDays(1);
                //cookieHost.Domain = Request.RequestUri.Host;
                cookieHost.Path = "/";
                message.Headers.AddCookies(new[] { cookieSession, cookieHost });
                return message;
            }
            catch (Exception e)
            {
                var resEx = e;
                var status = HttpStatusCode.BadRequest;
                var ex = e as StreamApiException;
                if (ex != null)
                {
                    status = HttpStatusCode.BadRequest;
                    resEx = ex;
                    var wex = ex.WebException;
                    if (wex != null)
                    {
                        if (wex.Status == WebExceptionStatus.ProtocolError)
                        {
                            var response = wex.Response as HttpWebResponse;
                            if (response != null)
                            {
                                status = response.StatusCode;
                                resEx = wex;
                            }
                        }
                    }
                }

                return Request.CreateErrorResponse(status, resEx);
            }
        }
            public override void OnActionExecuted(HttpActionExecutedContext context)
            {
                if (context.Response == null) return;

                var objectContent = context.Response.Content as ObjectContent;
                if (objectContent == null || objectContent.Value == null) return;

                //there is a result, set the outgoing cookie
                var cookie = new CookieHeaderValue("UMB_UPDCHK", "1")
                    {
                        Path = "/",
                        Expires = DateTimeOffset.Now.AddDays(GlobalSettings.VersionCheckPeriod),
                        HttpOnly = true,
                        Secure = GlobalSettings.UseSSL
                    };
                context.Response.Headers.AddCookies(new[] { cookie });
            }
 //This will be the url where the clients will get poll for messages
 public HttpResponseMessage Get(HttpRequestMessage request)
 {
     var response = request.CreateResponse();
     response.Content = new PushStreamContent(OnStreamAvailable, "text/event-stream");
     string newId;
     if (IncommingConnectionAssigningId != null)
         newId = IncommingConnectionAssigningId();
     else
         newId = null;
     if(string.IsNullOrWhiteSpace(newId))
         newId = Guid.NewGuid().ToString();
     response.Content.Headers.ContentLanguage.Add(string.Format("id-{0}",newId)); //This is to store the userid, the we will use a cookie
     CookieHeaderValue cookie = new CookieHeaderValue ("clientid","sample");
     IEnumerable<CookieHeaderValue> cookies = new List<CookieHeaderValue>();
     response.Headers.AddCookies(cookies);
     return response;
 }
        private static bool ParseCookieSegment(CookieHeaderValue instance, string segment)
        {
            if (String.IsNullOrWhiteSpace(segment))
            {
                return(true);
            }

            string[] nameValue = segment.Split(nameValueSeparator, 2);
            if (nameValue.Length < 1 || String.IsNullOrWhiteSpace(nameValue[0]))
            {
                return(false);
            }

            string name = nameValue[0].Trim();

            if (String.Equals(name, ExpiresToken, StringComparison.OrdinalIgnoreCase))
            {
                string         value = GetSegmentValue(nameValue, null);
                DateTimeOffset expires;
                if (FormattingUtilities.TryParseDate(value, out expires))
                {
                    instance.Expires = expires;
                    return(true);
                }
                return(false);
            }
            else if (String.Equals(name, MaxAgeToken, StringComparison.OrdinalIgnoreCase))
            {
                string value = GetSegmentValue(nameValue, null);
                int    maxAge;
                if (FormattingUtilities.TryParseInt32(value, out maxAge))
                {
                    instance.MaxAge = new TimeSpan(0, 0, maxAge);
                    return(true);
                }
                return(false);
            }
            else if (String.Equals(name, DomainToken, StringComparison.OrdinalIgnoreCase))
            {
                instance.Domain = GetSegmentValue(nameValue, null);
                return(true);
            }
            else if (String.Equals(name, PathToken, StringComparison.OrdinalIgnoreCase))
            {
                instance.Path = GetSegmentValue(nameValue, DefaultPath);
                return(true);
            }
            else if (String.Equals(name, SecureToken, StringComparison.OrdinalIgnoreCase))
            {
                string value = GetSegmentValue(nameValue, null);
                if (!String.IsNullOrWhiteSpace(value))
                {
                    return(false);
                }
                instance.Secure = true;
                return(true);
            }
            else if (String.Equals(name, HttpOnlyToken, StringComparison.OrdinalIgnoreCase))
            {
                string value = GetSegmentValue(nameValue, null);
                if (!String.IsNullOrWhiteSpace(value))
                {
                    return(false);
                }
                instance.HttpOnly = true;
                return(true);
            }
            else
            {
                string value = GetSegmentValue(nameValue, null);

                // We read the cookie segment as form data
                try
                {
                    FormDataCollection  formData = new FormDataCollection(value);
                    NameValueCollection values   = formData.ReadAsNameValueCollection();
                    CookieState         cookie   = new CookieState(name, values);
                    instance.Cookies.Add(cookie);
                    return(true);
                }
                catch
                {
                    return(false);
                }
            }
        }