/// <summary>
        ///   Save the session identifier in the specified context.
        /// </summary>
        /// <param name="sessionId">The identifier of the session.</param>
        /// <param name="context">The current context.</param>
        public void SaveSessionId(SessionId sessionId, NancyContext context)
        {
            if (sessionId == null)
            {
                throw new ArgumentNullException("sessionId");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (context.Response == null)
            {
                throw new ArgumentException("The specified context does not contain a response to modify", "context");
            }
            if (sessionId.IsEmpty)
            {
                throw new ArgumentException("The specified session id cannot be empty", "sessionId");
            }

            var encryptedSessionId = _encryptionProvider.Encrypt(sessionId.Value.ToString());
            var hmacBytes          = _hmacProvider.GenerateHmac(encryptedSessionId);

            var sessionIdentificationData = new SessionIdentificationData {
                SessionId = encryptedSessionId, Hmac = hmacBytes
            };

            var cookie = _cookieFactory.CreateCookie(CookieName, Domain, Path, sessionIdentificationData);

            context.Response.WithCookie(cookie);
        }
    public void ModifyResponseToRedirectToSessionAwareUrl(NancyContext context, SessionIdentificationData sessionIdentificationData, string parameterName) {
      if (context == null) throw new ArgumentNullException("context");
      if (sessionIdentificationData == null) throw new ArgumentNullException("sessionIdentificationData");
      if (string.IsNullOrWhiteSpace(parameterName)) throw new ArgumentNullException("parameterName");
      if (context.Request == null) throw new ArgumentException("The specified context does not contain a request", "context");
      if (context.Response == null) throw new ArgumentException("The specified context does not contain a response", "context");

      var originalUri = (Uri) context.Request.Url;
      var uriBuilder = new UriBuilder(originalUri);
      var queryParameters = HttpUtility.ParseQueryString(uriBuilder.Query);
      queryParameters.Set(parameterName, sessionIdentificationData.ToString());

      var newQueryString = string.Empty;
      if (queryParameters.Count > 0) {
        var newQueryBuilder = new StringBuilder();
        foreach (var paramName in queryParameters.AllKeys) {
          newQueryBuilder.Append(string.Format("{0}={1}&", paramName, HttpUtility.UrlEncode(queryParameters[paramName])));
        }
        newQueryString = newQueryBuilder.ToString().TrimEnd('&');
      }
      uriBuilder.Query = newQueryString;
      var redirectUrl = uriBuilder.ToString();

      context.Response.StatusCode = HttpStatusCode.Found;
      context.Response.Headers["Location"] = redirectUrl;
    }
    public ResponseManipulatorForSessionFixture() {
      _responseManipulatorForSession = new ResponseManipulatorForSession();

      _context = new NancyContext {Response = new Response(), Request = new Request("GET", "http://www.google.be")};
      _sessionIdentificationData = new SessionIdentificationData {SessionId = "01SessionId", Hmac = new byte[] {211, 81, 204, 0, 47, 124}};
      _parameterName = "SID";
    }
예제 #4
0
        /// <summary>
        ///   Save the session identifier in the specified context.
        /// </summary>
        /// <param name="sessionId">The identifier of the session.</param>
        /// <param name="context">The current context.</param>
        public void SaveSessionId(SessionId sessionId, NancyContext context)
        {
            if (sessionId == null)
            {
                throw new ArgumentNullException("sessionId");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (context.Request == null)
            {
                throw new ArgumentException("The specified context does not contain a request", "context");
            }
            if (sessionId.IsEmpty)
            {
                throw new ArgumentException("The specified session id cannot be empty", "sessionId");
            }

            // Redirect the client to the same url, with the session Id as a query string parameter, if needed
            if (sessionId.IsNew)
            {
                var encryptedSessionId = _encryptionProvider.Encrypt(sessionId.Value.ToString());
                var hmacBytes          = _hmacProvider.GenerateHmac(encryptedSessionId);

                var sessionIdentificationData = new SessionIdentificationData {
                    SessionId = encryptedSessionId, Hmac = hmacBytes
                };

                _responseManipulatorForSession.ModifyResponseToRedirectToSessionAwareUrl(context, sessionIdentificationData, ParameterName);
            }
        }
    public CookieFactoryFixture() {
      _cookieFactory = new CookieFactory();

      _cookieName = "TheCookieName";
      _cookieValue = "01HMAC98%02SessionId";
      _cookieValueEncoded = "01HMAC98%2502SessionId";
      _sessionIdentificationData = new SessionIdentificationData {SessionId = "%02SessionId", Hmac = new byte[] {211, 81, 204, 0, 47, 124}};
      _cookieDomain = ".nascar.com";
      _cookiePath = "/schedule/";
    }
예제 #6
0
        public ResponseManipulatorForSessionFixture()
        {
            _responseManipulatorForSession = new ResponseManipulatorForSession();

            _context = new NancyContext {
                Response = new Response(), Request = new Request("GET", "http://www.google.be")
            };
            _sessionIdentificationData = new SessionIdentificationData {
                SessionId = "01SessionId", Hmac = new byte[] { 211, 81, 204, 0, 47, 124 }
            };
            _parameterName = "SID";
        }
예제 #7
0
        public CookieFactoryFixture()
        {
            _cookieFactory = new CookieFactory();

            _cookieName                = "TheCookieName";
            _cookieValue               = "01HMAC98%02SessionId";
            _cookieValueEncoded        = "01HMAC98%2502SessionId";
            _sessionIdentificationData = new SessionIdentificationData {
                SessionId = "%02SessionId", Hmac = new byte[] { 211, 81, 204, 0, 47, 124 }
            };
            _cookieDomain = ".nascar.com";
            _cookiePath   = "/schedule/";
        }
    public SessionIdentificationDataProviderFixture() {
      _parameterName = "TheParamName";
      _hmacProvider = A.Fake<IHmacProvider>();
      _sessionIdentificationDataProvider = new SessionIdentificationDataProvider(_hmacProvider);

      _hmacString = "01HMAC98";
      _encryptedSessionIdString = "s%26%c2%a7%c2%a7ionId";
      _validRequest = new Request("GET", string.Format("http://www.google.be?{0}={1}{2}", _parameterName, _hmacString, _encryptedSessionIdString));

      _expectedResult = new SessionIdentificationData {SessionId = "s&§§ionId", Hmac = new byte[] {211, 81, 204, 0, 47, 124}};

      A.CallTo(() => _hmacProvider.HmacLength).Returns(6);
    }
    public SessionIdentificationDataProviderFixture() {
      _cookieName = "TheCookieName";
      _hmacProvider = A.Fake<IHmacProvider>();
      _sessionIdentificationDataProvider = new SessionIdentificationDataProvider(_hmacProvider);

      _validRequest = new Request("GET", "http://www.google.be");
      _hmacString = "01HMAC98";
      _encryptedSessionIdString = "%02Session+Id";
      _validRequest.Cookies.Add(_cookieName, _hmacString + _encryptedSessionIdString);

      _expectedResult = new SessionIdentificationData {SessionId = "%02Session+Id", Hmac = new byte[] {211, 81, 204, 0, 47, 124}};

      A.CallTo(() => _hmacProvider.HmacLength).Returns(6);
    }
            public void When_cookie_does_not_have_a_valid_hmac_then_returns_new_session_id()
            {
                var cookieData = new SessionIdentificationData {
                    SessionId = "ABCSomeEncryptedSessionIdXYZ", Hmac = new byte[] { 1, 2, 3 }
                };

                A.CallTo(() => _fakeSessionIdentificationDataProvider.ProvideDataFromCookie(_context.Request, _cookieName)).Returns(cookieData);
                A.CallTo(() => _fakeHmacValidator.IsValidHmac(cookieData)).Returns(false);

                var actual = _bySessionIdCookieIdentificationMethod.GetCurrentSessionId(_context);

                Assert.Equal(_newSessionId, actual);
                A.CallTo(() => _fakeSessionIdFactory.CreateNew()).MustHaveHappened();
                A.CallTo(() => _fakeSessionIdFactory.CreateFrom(A <string> ._)).MustNotHaveHappened();
            }
        public SessionIdentificationDataProviderFixture()
        {
            _parameterName = "TheParamName";
            _hmacProvider  = A.Fake <IHmacProvider>();
            _sessionIdentificationDataProvider = new SessionIdentificationDataProvider(_hmacProvider);

            _hmacString = "01HMAC98";
            _encryptedSessionIdString = "s%26%c2%a7%c2%a7ionId";
            _validRequest             = new Request("GET", string.Format("http://www.google.be?{0}={1}{2}", _parameterName, _hmacString, _encryptedSessionIdString));

            _expectedResult = new SessionIdentificationData {
                SessionId = "s&§§ionId", Hmac = new byte[] { 211, 81, 204, 0, 47, 124 }
            };

            A.CallTo(() => _hmacProvider.HmacLength).Returns(6);
        }
            public void When_decrypted_session_id_is_not_valid_then_returns_new_session_id()
            {
                var sessionIdentificationData = new SessionIdentificationData {
                    SessionId = "ABCSomeEncryptedSessionIdXYZ", Hmac = new byte[] { 1, 2, 3 }
                };

                A.CallTo(() => _fakeSessionIdentificationDataProvider.ProvideDataFromQuery(_context.Request, _parameterName)).Returns(sessionIdentificationData);
                A.CallTo(() => _fakeHmacValidator.IsValidHmac(sessionIdentificationData)).Returns(true);
                A.CallTo(() => _fakeEncryptionProvider.Decrypt(sessionIdentificationData.SessionId)).Returns(string.Empty);

                var actual = _byQueryStringParamIdentificationMethod.GetCurrentSessionId(_context);

                Assert.Equal(_newSessionId, actual);
                A.CallTo(() => _fakeSessionIdFactory.CreateNew()).MustHaveHappened();
                A.CallTo(() => _fakeSessionIdFactory.CreateFrom(A <string> ._)).MustNotHaveHappened();
            }
        public SessionIdentificationDataProviderFixture()
        {
            _cookieName   = "TheCookieName";
            _hmacProvider = A.Fake <IHmacProvider>();
            _sessionIdentificationDataProvider = new SessionIdentificationDataProvider(_hmacProvider);

            _validRequest             = new Request("GET", "http://www.google.be");
            _hmacString               = "01HMAC98";
            _encryptedSessionIdString = "%02Session+Id";
            _validRequest.Cookies.Add(_cookieName, _hmacString + _encryptedSessionIdString);

            _expectedResult = new SessionIdentificationData {
                SessionId = "%02Session+Id", Hmac = new byte[] { 211, 81, 204, 0, 47, 124 }
            };

            A.CallTo(() => _hmacProvider.HmacLength).Returns(6);
        }
        public void ModifyResponseToRedirectToSessionAwareUrl(NancyContext context, SessionIdentificationData sessionIdentificationData, string parameterName)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (sessionIdentificationData == null)
            {
                throw new ArgumentNullException("sessionIdentificationData");
            }
            if (string.IsNullOrWhiteSpace(parameterName))
            {
                throw new ArgumentNullException("parameterName");
            }
            if (context.Request == null)
            {
                throw new ArgumentException("The specified context does not contain a request", "context");
            }
            if (context.Response == null)
            {
                throw new ArgumentException("The specified context does not contain a response", "context");
            }

            var originalUri     = (Uri)context.Request.Url;
            var uriBuilder      = new UriBuilder(originalUri);
            var queryParameters = HttpUtility.ParseQueryString(uriBuilder.Query);

            queryParameters.Set(parameterName, sessionIdentificationData.ToString());

            var newQueryString = string.Empty;

            if (queryParameters.Count > 0)
            {
                var newQueryBuilder = new StringBuilder();
                foreach (var paramName in queryParameters.AllKeys)
                {
                    newQueryBuilder.Append(string.Format("{0}={1}&", paramName, HttpUtility.UrlEncode(queryParameters[paramName])));
                }
                newQueryString = newQueryBuilder.ToString().TrimEnd('&');
            }
            uriBuilder.Query = newQueryString;
            var redirectUrl = uriBuilder.ToString();

            context.Response.StatusCode          = HttpStatusCode.Found;
            context.Response.Headers["Location"] = redirectUrl;
        }
            public void When_decrypted_session_id_is_not_a_valid_guid_then_returns_new_session_id()
            {
                const string invalidDecryptedSessionId = "This is not a valid guid!";
                var          cookieData = new SessionIdentificationData {
                    SessionId = "ABCSomeEncryptedSessionIdXYZ", Hmac = new byte[] { 1, 2, 3 }
                };

                A.CallTo(() => _fakeSessionIdentificationDataProvider.ProvideDataFromCookie(_context.Request, _cookieName)).Returns(cookieData);
                A.CallTo(() => _fakeHmacValidator.IsValidHmac(cookieData)).Returns(true);
                A.CallTo(() => _fakeEncryptionProvider.Decrypt(cookieData.SessionId)).Returns(invalidDecryptedSessionId);
                A.CallTo(() => _fakeSessionIdFactory.CreateFrom(invalidDecryptedSessionId)).Returns(null);

                var actual = _bySessionIdCookieIdentificationMethod.GetCurrentSessionId(_context);

                Assert.Equal(_newSessionId, actual);
                A.CallTo(() => _fakeSessionIdFactory.CreateNew()).MustHaveHappened();
                A.CallTo(() => _fakeSessionIdFactory.CreateFrom(invalidDecryptedSessionId)).MustHaveHappened();
            }
            public void When_decrypted_session_id_is_valid_then_returns_session_id_from_cookie()
            {
                var expectedSessionId  = new SessionId(Guid.NewGuid(), false);
                var decryptedSessionId = expectedSessionId.Value.ToString();
                var cookieData         = new SessionIdentificationData {
                    SessionId = "ABCSomeEncryptedSessionIdXYZ", Hmac = new byte[] { 1, 2, 3 }
                };

                A.CallTo(() => _fakeSessionIdentificationDataProvider.ProvideDataFromCookie(_context.Request, _cookieName)).Returns(cookieData);
                A.CallTo(() => _fakeHmacValidator.IsValidHmac(cookieData)).Returns(true);
                A.CallTo(() => _fakeEncryptionProvider.Decrypt(cookieData.SessionId)).Returns(decryptedSessionId);
                A.CallTo(() => _fakeSessionIdFactory.CreateFrom(decryptedSessionId)).Returns(expectedSessionId);

                var actual = _bySessionIdCookieIdentificationMethod.GetCurrentSessionId(_context);

                Assert.Equal(expectedSessionId, actual);
                A.CallTo(() => _fakeSessionIdFactory.CreateNew()).MustNotHaveHappened();
                A.CallTo(() => _fakeSessionIdFactory.CreateFrom(decryptedSessionId)).MustHaveHappened();
            }
예제 #17
0
        public INancyCookie CreateCookie(string cookieName, string cookieDomain, string cookiePath, SessionIdentificationData sessionIdentificationData)
        {
            if (sessionIdentificationData == null)
            {
                throw new ArgumentNullException("sessionIdentificationData");
            }
            if (string.IsNullOrWhiteSpace(cookieName))
            {
                throw new ArgumentNullException("cookieName");
            }

            return(new NancyCookie(cookieName, sessionIdentificationData.ToString(), true)
            {
                Domain = cookieDomain, Path = cookiePath
            });
        }
      public void When_decrypted_session_id_is_not_valid_then_returns_new_session_id() {
        var cookieData = new SessionIdentificationData {SessionId = "ABCSomeEncryptedSessionIdXYZ", Hmac = new byte[] {1, 2, 3}};

        A.CallTo(() => _fakeSessionIdentificationDataProvider.ProvideDataFromCookie(_context.Request, _cookieName)).Returns(cookieData);
        A.CallTo(() => _fakeHmacValidator.IsValidHmac(cookieData)).Returns(true);
        A.CallTo(() => _fakeEncryptionProvider.Decrypt(cookieData.SessionId)).Returns(string.Empty);

        var actual = _bySessionIdCookieIdentificationMethod.GetCurrentSessionId(_context);

        Assert.Equal(_newSessionId, actual);
        A.CallTo(() => _fakeSessionIdFactory.CreateNew()).MustHaveHappened();
        A.CallTo(() => _fakeSessionIdFactory.CreateFrom(A<string>._)).MustNotHaveHappened();
      }
    public INancyCookie CreateCookie(string cookieName, string cookieDomain, string cookiePath, SessionIdentificationData sessionIdentificationData) {
      if (sessionIdentificationData == null) throw new ArgumentNullException("sessionIdentificationData");
      if (string.IsNullOrWhiteSpace(cookieName)) throw new ArgumentNullException("cookieName");

      return new NancyCookie(cookieName, sessionIdentificationData.ToString(), true) {Domain = cookieDomain, Path = cookiePath};
    }
    /// <summary>
    ///   Save the session identifier in the specified context.
    /// </summary>
    /// <param name="sessionId">The identifier of the session.</param>
    /// <param name="context">The current context.</param>
    public void SaveSessionId(SessionId sessionId, NancyContext context) {
      if (sessionId == null) throw new ArgumentNullException("sessionId");
      if (context == null) throw new ArgumentNullException("context");
      if (context.Request == null) throw new ArgumentException("The specified context does not contain a request", "context");
      if (sessionId.IsEmpty) throw new ArgumentException("The specified session id cannot be empty", "sessionId");

      // Redirect the client to the same url, with the session Id as a query string parameter, if needed
      if (sessionId.IsNew) {
        var encryptedSessionId = _encryptionProvider.Encrypt(sessionId.Value.ToString());
        var hmacBytes = _hmacProvider.GenerateHmac(encryptedSessionId);

        var sessionIdentificationData = new SessionIdentificationData {SessionId = encryptedSessionId, Hmac = hmacBytes};

        _responseManipulatorForSession.ModifyResponseToRedirectToSessionAwareUrl(context, sessionIdentificationData, ParameterName);
      }
    }
    /// <summary>
    ///   Save the session identifier in the specified context.
    /// </summary>
    /// <param name="sessionId">The identifier of the session.</param>
    /// <param name="context">The current context.</param>
    public void SaveSessionId(SessionId sessionId, NancyContext context) {
      if (sessionId == null) throw new ArgumentNullException("sessionId");
      if (context == null) throw new ArgumentNullException("context");
      if (context.Response == null) throw new ArgumentException("The specified context does not contain a response to modify", "context");
      if (sessionId.IsEmpty) throw new ArgumentException("The specified session id cannot be empty", "sessionId");

      var encryptedSessionId = _encryptionProvider.Encrypt(sessionId.Value.ToString());
      var hmacBytes = _hmacProvider.GenerateHmac(encryptedSessionId);

      var sessionIdentificationData = new SessionIdentificationData {SessionId = encryptedSessionId, Hmac = hmacBytes};

      var cookie = _cookieFactory.CreateCookie(CookieName, Domain, Path, sessionIdentificationData);
      context.Response.WithCookie(cookie);
    }
      public void When_querystring_does_not_have_a_valid_hmac_then_returns_new_session_id() {
        var sessionIdentificationData = new SessionIdentificationData {SessionId = "ABCSomeEncryptedSessionIdXYZ", Hmac = new byte[] {1, 2, 3}};

        A.CallTo(() => _fakeSessionIdentificationDataProvider.ProvideDataFromQuery(_context.Request, _parameterName)).Returns(sessionIdentificationData);
        A.CallTo(() => _fakeHmacValidator.IsValidHmac(sessionIdentificationData)).Returns(false);

        var actual = _byQueryStringParamIdentificationMethod.GetCurrentSessionId(_context);

        Assert.Equal(_newSessionId, actual);
        A.CallTo(() => _fakeSessionIdFactory.CreateNew()).MustHaveHappened();
        A.CallTo(() => _fakeSessionIdFactory.CreateFrom(A<string>._)).MustNotHaveHappened();
      }
      public void When_decrypted_session_id_is_not_a_valid_guid_then_returns_new_session_id() {
        const string invalidDecryptedSessionId = "This is not a valid guid!";
        var sessionIdentificationData = new SessionIdentificationData {SessionId = "ABCSomeEncryptedSessionIdXYZ", Hmac = new byte[] {1, 2, 3}};

        A.CallTo(() => _fakeSessionIdentificationDataProvider.ProvideDataFromQuery(_context.Request, _parameterName)).Returns(sessionIdentificationData);
        A.CallTo(() => _fakeHmacValidator.IsValidHmac(sessionIdentificationData)).Returns(true);
        A.CallTo(() => _fakeEncryptionProvider.Decrypt(sessionIdentificationData.SessionId)).Returns(invalidDecryptedSessionId);
        A.CallTo(() => _fakeSessionIdFactory.CreateFrom(invalidDecryptedSessionId)).Returns(null);

        var actual = _byQueryStringParamIdentificationMethod.GetCurrentSessionId(_context);

        Assert.Equal(_newSessionId, actual);
        A.CallTo(() => _fakeSessionIdFactory.CreateNew()).MustHaveHappened();
        A.CallTo(() => _fakeSessionIdFactory.CreateFrom(invalidDecryptedSessionId)).MustHaveHappened();
      }
      public void When_decrypted_session_id_is_valid_then_returns_session_id_from_querystring() {
        var expectedSessionId = new SessionId(Guid.NewGuid(), false);
        var decryptedSessionId = expectedSessionId.Value.ToString();
        var sessionIdentificationData = new SessionIdentificationData {SessionId = "ABCSomeEncryptedSessionIdXYZ", Hmac = new byte[] {1, 2, 3}};

        A.CallTo(() => _fakeSessionIdentificationDataProvider.ProvideDataFromQuery(_context.Request, _parameterName)).Returns(sessionIdentificationData);
        A.CallTo(() => _fakeHmacValidator.IsValidHmac(sessionIdentificationData)).Returns(true);
        A.CallTo(() => _fakeEncryptionProvider.Decrypt(sessionIdentificationData.SessionId)).Returns(decryptedSessionId);
        A.CallTo(() => _fakeSessionIdFactory.CreateFrom(decryptedSessionId)).Returns(expectedSessionId);

        var actual = _byQueryStringParamIdentificationMethod.GetCurrentSessionId(_context);

        Assert.Equal(expectedSessionId, actual);
        A.CallTo(() => _fakeSessionIdFactory.CreateNew()).MustNotHaveHappened();
        A.CallTo(() => _fakeSessionIdFactory.CreateFrom(decryptedSessionId)).MustHaveHappened();
      }