/// <summary> /// Parse a header /// </summary> /// <param name="name">Name of header.</param> /// <param name="reader">Reader containing value.</param> /// <returns>HTTP Header</returns> /// <exception cref="FormatException">Header value is not of the expected format.</exception> public IHeader Parse(string name, ITextParser reader) { //key: "value"; key: "value" var cookies = new HttpCookieCollection(); while (!reader.EndOfFile) { // read name string cookieName = reader.ReadToEnd("=;"); // cookie with value? if (reader.Current == '=') { reader.Consume(); reader.ConsumeWhiteSpaces(); // is value quoted or not? string value = reader.Current == '"' ? reader.ReadQuotedString() : reader.ReadToEnd(";"); cookies.Add(new HttpCookie(cookieName, value)); } //else // cookies.Add(new RequestCookie(cookieName, string.Empty)); // consume whitespaces and cookie separator reader.ConsumeWhiteSpaces(';'); } return new CookieHeader(cookies); }
private static void UpdateCookie(string cookie_name, string cookie_value, HttpCookieCollection cookies) { HttpCookie cookie = cookies.Get(cookie_name); if (null == cookie) { cookie = new HttpCookie(cookie_name); } cookie.Value = cookie_value; cookies.Set(cookie); }
public bool HasFacebookCookies(HttpCookieCollection cookies) { string cookiePrefix = FacebookAPIKey + "_"; foreach (string cookieName in cookies) { if (cookieName.StartsWith(cookiePrefix)) return true; } return false; }
public void IsAuthenticatedReturnsFalseIfAuthCookieNotInCollection() { // Arrange var mockRequest = new Mock<HttpRequestBase>(); var cookies = new HttpCookieCollection(); mockRequest.Setup(m => m.Cookies).Returns(cookies); // Act bool authorized = AdminSecurity.IsAuthenticated(mockRequest.Object); // Assert Assert.False(authorized); }
public void PersistFilterCreatesCookieIfItDoesNotExist() { // Arrange var cookies = new HttpCookieCollection(); var response = new Mock<HttpResponseBase>(); response.Setup(c => c.Cookies).Returns(cookies); // Act PageUtils.PersistFilter(response.Object, "my-cookie", new Dictionary<string, string>()); // Assert Assert.NotNull(cookies["my-cookie"]); }
public void SetAuthCookieAddsAuthCookieToResponseCollection() { // Arrange var mockResponse = new Mock<HttpResponseBase>(); var cookies = new HttpCookieCollection(); mockResponse.Setup(m => m.Cookies).Returns(cookies); // Act AdminSecurity.SetAuthCookie(mockResponse.Object); // Assert Assert.NotNull(cookies[".ASPXADMINAUTH"]); }
internal CookieValueProvider(HttpCookieCollection collection, HttpCookieCollection unvalidatedCollection, CultureInfo culture) { if (collection == null) { throw new ArgumentNullException("collection"); } _culture = culture; _prefixes = new PrefixContainer(collection.Keys.Cast<string>()); _validatedCollection = collection; _unvalidatedCollection = unvalidatedCollection ?? collection; foreach (string key in collection) { if (key != null) { _values[key] = new ValueProviderResultPlaceholder(key, this); } } }
public void GetFilterValueReturnsValueFromCookieIfQueryStringDoesNotContainKey() { // Arrange const string key = "my-key"; const string value = "my-cookie-value"; var request = new Mock<HttpRequestBase>(); request.Setup(c => c.QueryString).Returns(new NameValueCollection()); var cookies = new HttpCookieCollection(); var cookie = new HttpCookie("foo"); cookie[key] = value; cookies.Add(cookie); request.Setup(c => c.Cookies).Returns(cookies); // Act var returnedValue = PageUtils.GetFilterValue(request.Object, "foo", key); // Assert Assert.Equal(value, returnedValue); }
public SortedList<string, string> GetFacebookCookies(HttpCookieCollection cookies) { SortedList<string, string> sortedCookies = new SortedList<string, string>(); string cookiePrefix = FacebookAPIKey + "_"; foreach (string cookieName in cookies) { if (cookieName.StartsWith(cookiePrefix)) { var cookie = cookies[cookieName]; sortedCookies.Add(cookie.Name.Substring(cookiePrefix.Length), cookie.Value); } } if (sortedCookies.Count == 0) { throw new Exception("Facebook Cookies not set."); } return sortedCookies; }
public void GetFilterValueReturnsValueFromQueryString() { // Arrange const string key = "my-key"; const string requestValue = "my-request-value"; const string cookieValue = "my-cookie-value"; var request = new Mock<HttpRequestBase>(); var queryString = new NameValueCollection(); queryString[key] = requestValue; request.Setup(c => c.QueryString).Returns(queryString); var cookies = new HttpCookieCollection(); var cookie = new HttpCookie("foo"); cookie[key] = cookieValue; request.Setup(c => c.Cookies).Returns(cookies); // Act var returnedValue = PageUtils.GetFilterValue(request.Object, "foo", key); // Assert Assert.Equal(requestValue, returnedValue); }
public static void Rest(string appsesssid,HttpCookieCollection cookies) { try { string session_param_name = "ASPSESSID"; string session_cookie_name = "ASP.NET_SessionId"; if (appsesssid != null) { UpdateCookie(session_cookie_name, appsesssid,cookies); } else if (HttpContext.Current.Request.QueryString[session_param_name] != null) { UpdateCookie(session_cookie_name, appsesssid,cookies); } } catch { } try { string auth_param_name = "AUTHID"; string auth_cookie_name = System.Web.Security.FormsAuthentication.FormsCookieName; if (HttpContext.Current.Request.Form[auth_param_name] != null) { UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name],cookies); } else if (HttpContext.Current.Request.QueryString[auth_param_name] != null) { UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name],cookies); } } catch { } }
internal static Mock<HttpContextBase> CreateCookieContext(HttpCookie requestCookie = null, HttpCookie responseCookie = null) { Mock<HttpContextBase> context = new Mock<HttpContextBase>(); HttpCookieCollection requestCookies = new HttpCookieCollection(); if (requestCookie != null) { requestCookies.Add(requestCookie); } HttpCookieCollection responseCookies = new HttpCookieCollection(); if (responseCookie != null) { responseCookies.Add(responseCookie); } context.Setup(c => c.Request.Cookies).Returns(requestCookies); context.Setup(c => c.Response.Cookies).Returns(responseCookies); context.Setup(c => c.Items).Returns(new Hashtable()); return context; }
public FakeHttpContext(FakePrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems,RouteData routeData) { _principal = principal; _formParams = formParams; _queryStringParams = queryStringParams; _cookies = cookies; _sessionItems = sessionItems; _response = new FakeHttpResponse(); _request = new FakeHttpRequest(_formParams, _queryStringParams, _cookies,this,routeData); _items = new FakeDictionary(); }
public FakeHttpRequest(NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies) { _formParams = formParams; _queryStringParams = queryStringParams; _cookies = cookies; }
public void SaveCookieToken(bool requireSsl, bool? expectedCookieSecureFlag) { // Arrange AntiForgeryToken token = new AntiForgeryToken(); HttpCookieCollection cookies = new HttpCookieCollection(); bool defaultCookieSecureValue = expectedCookieSecureFlag ?? new HttpCookie("name", "value").Secure; // pulled from config; set by ctor Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>(); mockHttpContext.Setup(o => o.Response.Cookies).Returns(cookies); Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>(); mockSerializer.Setup(o => o.Serialize(token)).Returns("serialized-value"); MockAntiForgeryConfig config = new MockAntiForgeryConfig() { CookieName = "cookie-name", RequireSSL = requireSsl }; AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore( config: config, serializer: mockSerializer.Object); // Act tokenStore.SaveCookieToken(mockHttpContext.Object, token); // Assert Assert.Equal(1, cookies.Count); HttpCookie cookie = cookies["cookie-name"]; Assert.NotNull(cookie); Assert.Equal("serialized-value", cookie.Value); Assert.True(cookie.HttpOnly); Assert.Equal(defaultCookieSecureValue, cookie.Secure); }
/// <summary> /// Initializes a new instance of the <see cref="HttpResponse"/> class. /// </summary> /// <param name="statusCode">The status code.</param> /// <param name="reasonPhrase">The reason phrase.</param> /// <param name="httpVersion">The HTTP version.</param> public HttpResponse(HttpStatusCode statusCode, string reasonPhrase, string httpVersion) : base(statusCode, reasonPhrase, httpVersion) { Cookies = new HttpCookieCollection<IResponseCookie>(); }
/* goodB2G() - use badsource and goodsink by changing the second "if" so that * both branches use the GoodSink */ private void GoodB2G(HttpRequest req, HttpResponse resp) { int data; if (IO.StaticReturnsTrueOrFalse()) { data = int.MinValue; /* initialize data in case there are no cookies */ /* Read data from cookies */ { HttpCookieCollection cookieSources = req.Cookies; if (cookieSources != null) { /* POTENTIAL FLAW: Read data from the first cookie value */ string stringNumber = cookieSources[0].Value; try { data = int.Parse(stringNumber.Trim()); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception reading data from cookie"); } } } } else { data = int.MinValue; /* initialize data in case there are no cookies */ /* Read data from cookies */ { HttpCookieCollection cookieSources = req.Cookies; if (cookieSources != null) { /* POTENTIAL FLAW: Read data from the first cookie value */ string stringNumber = cookieSources[0].Value; try { data = int.Parse(stringNumber.Trim()); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception reading data from cookie"); } } } } if (IO.StaticReturnsTrueOrFalse()) { /* FIX: test for a zero modulus */ if (data != 0) { IO.WriteLine("100%" + data + " = " + (100 % data) + "\n"); } else { IO.WriteLine("This would result in a modulo by zero"); } } else { /* FIX: test for a zero modulus */ if (data != 0) { IO.WriteLine("100%" + data + " = " + (100 % data) + "\n"); } else { IO.WriteLine("This would result in a modulo by zero"); } } }
public FakeHttpContext(string relativeUrl, IPrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems) : this(relativeUrl, (string)null, principal, formParams, queryStringParams, cookies, sessionItems) { }
/* goodB2G1() - use badsource and goodsink by changing second IO.STATIC_READONLY_FIVE==5 to IO.STATIC_READONLY_FIVE!=5 */ private void GoodB2G1(HttpRequest req, HttpResponse resp) { string data; if (IO.STATIC_READONLY_FIVE == 5) { data = ""; /* initialize data in case there are no cookies */ /* Read data from cookies */ { HttpCookieCollection cookieSources = req.Cookies; if (cookieSources != null) { /* POTENTIAL FLAW: Read data from the first cookie value */ data = cookieSources[0].Value; } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.STATIC_READONLY_FIVE != 5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); } else { int?result = null; try { using (SqlConnection dbConnection = IO.GetDBConnection()) { dbConnection.Open(); using (SqlCommand goodSqlCommand = new SqlCommand(null, dbConnection)) { goodSqlCommand.CommandText = "insert into users (status) values ('updated') where name=@name"; /* FIX: Use prepared statement and ExecuteNonQuery (properly) */ SqlParameter nameParam = new SqlParameter("@name", SqlDbType.VarChar, 0); nameParam.Value = data; goodSqlCommand.Parameters.Add(nameParam); goodSqlCommand.Prepare(); result = goodSqlCommand.ExecuteNonQuery(); if (result != null) { IO.WriteLine("Name, " + data + ", updated successfully"); } else { IO.WriteLine("Unable to update records for user: "******"Error getting database connection", exceptSql); } } }
public async Task IndexMethodShouldBuildVMWithTrustAndAcademiesMatFinancingTypeByDefaultAsync() { var mockTrustSearchService = new Mock <ITrustSearchService>(); var mockHistoricalChartBuilder = new Mock <IHistoricalChartBuilder>(); var mockFinancialDataService = new Mock <IFinancialDataService>(); var mockFCService = new Mock <IFinancialCalculationsService>(); var mockDataCollectionManager = new Mock <IDataCollectionManager>(); var mockCookieManager = new Mock <ISchoolBenchmarkListService>(); var mockEdubaseDataService = new Mock <IContextDataService>(); var mockTrustHistoryService = new Mock <ITrustHistoryService>(); var request = new Mock <HttpRequestBase>(MockBehavior.Strict); var context = new Mock <HttpContextBase>(MockBehavior.Strict); context.SetupGet(x => x.Request).Returns(request.Object); var requestCookies = new HttpCookieCollection(); context.SetupGet(x => x.Request.Cookies).Returns(requestCookies); var rc = new RequestContext(context.Object, new RouteData()); var result = new List <AcademySummaryDataObject>() { new AcademySummaryDataObject() }; var GetAcademiesByCompanyNumberAsyncTask = Task.Run(() => result); mockFinancialDataService.Setup(m => m.GetAcademiesByCompanyNumberAsync(It.IsAny <string>(), It.IsAny <int>())) .Returns(GetAcademiesByCompanyNumberAsyncTask); var GetActiveTermsForMatCentralAsyncTask = Task.Run(() => new List <string> { "2015" }); mockFinancialDataService.Setup(m => m.GetActiveTermsForMatCentralAsync()) .Returns(GetActiveTermsForMatCentralAsyncTask); var GetLatestDataYearPerEstabTypeAsyncTask = Task.Run(() => 2015); mockFinancialDataService.Setup(m => m.GetLatestDataYearPerEstabTypeAsync(EstablishmentType.MAT)) .Returns(GetLatestDataYearPerEstabTypeAsyncTask); var GetLatestFinancialDataYearPerEstabTypeAsyncTask = Task.Run(() => 2015); mockDataCollectionManager.Setup(m => m.GetLatestFinancialDataYearPerEstabTypeAsync(EstablishmentType.MAT)) .Returns(GetLatestFinancialDataYearPerEstabTypeAsyncTask); var GetActiveTermsByDataGroupAsyncTask = Task.Run(() => new List <string> { "2015" }); mockDataCollectionManager.Setup(m => m.GetActiveTermsByDataGroupAsync(DataGroups.MATCentral)) .Returns(GetActiveTermsByDataGroupAsyncTask); mockHistoricalChartBuilder .Setup(m => m.Build(It.IsAny <TabType>(), It.IsAny <EstablishmentType>())) .Returns(new List <ChartViewModel>()); var mockCscpLookupService = new Mock <ICscpLookupService>(); var mockGiasLookupService = new Mock <IGiasLookupService>(); var controller = new TrustController(mockHistoricalChartBuilder.Object, mockFinancialDataService.Object, mockFCService.Object, mockEdubaseDataService.Object, null, mockCookieManager.Object, mockTrustHistoryService.Object, mockGiasLookupService.Object, mockCscpLookupService.Object); controller.ControllerContext = new ControllerContext(rc, controller); await controller.Index(123); mockFinancialDataService.Verify(m => m.GetTrustFinancialDataObjectByCompanyNoAsync(123, "2014 / 2015", MatFinancingType.TrustAndAcademies)); }
public void IndexMethodShouldRedirectToSchoolViewIfNoTrustFoundForCompanyNoButOneAcademyRelationIsFound() { var mockTrustSearchService = new Mock <ITrustSearchService>(); var mockHistoricalChartBuilder = new Mock <IHistoricalChartBuilder>(); var mockFinancialDataService = new Mock <IFinancialDataService>(); var mockFCService = new Mock <IFinancialCalculationsService>(); var mockDataCollectionManager = new Mock <IDataCollectionManager>(); var mockCookieManager = new Mock <ISchoolBenchmarkListService>(); var mockEdubaseDataService = new Mock <IContextDataService>(); var mockTrustHistoryService = new Mock <ITrustHistoryService>(); var request = new Mock <HttpRequestBase>(MockBehavior.Strict); var context = new Mock <HttpContextBase>(MockBehavior.Strict); context.SetupGet(x => x.Request).Returns(request.Object); var requestCookies = new HttpCookieCollection(); context.SetupGet(x => x.Request.Cookies).Returns(requestCookies); var rc = new RequestContext(context.Object, new RouteData()); var GetAcademiesByCompanyNumberAsyncTask = Task.Run(() => new List <AcademySummaryDataObject>() { new AcademySummaryDataObject() }); mockFinancialDataService.Setup(m => m.GetAcademiesByCompanyNumberAsync(It.IsAny <string>(), It.IsAny <int>())) .Returns(GetAcademiesByCompanyNumberAsyncTask); var GetActiveTermsForMatCentralAsyncTask = Task.Run(() => new List <string> { "2015" }); mockFinancialDataService.Setup(m => m.GetActiveTermsForMatCentralAsync()) .Returns(GetActiveTermsForMatCentralAsyncTask); var GetLatestDataYearPerEstabTypeAsyncTask = Task.Run(() => 2015); mockFinancialDataService.Setup(m => m.GetLatestDataYearPerEstabTypeAsync(EstablishmentType.MAT)) .Returns(GetLatestDataYearPerEstabTypeAsyncTask); var GetLatestFinancialDataYearPerEstabTypeAsyncTask = Task.Run(() => 2015); mockDataCollectionManager.Setup(m => m.GetLatestFinancialDataYearPerEstabTypeAsync(EstablishmentType.MAT)) .Returns(GetLatestFinancialDataYearPerEstabTypeAsyncTask); var GetActiveTermsByDataGroupAsyncTask = Task.Run(() => new List <string> { "2015" }); mockDataCollectionManager.Setup(m => m.GetActiveTermsByDataGroupAsync(DataGroups.MATCentral)) .Returns(GetActiveTermsByDataGroupAsyncTask); mockHistoricalChartBuilder .Setup(m => m.Build(It.IsAny <TabType>(), It.IsAny <EstablishmentType>())) .Returns(new List <ChartViewModel>()); var mockCscpLookupService = new Mock <ICscpLookupService>(); var mockGiasLookupService = new Mock <IGiasLookupService>(); var controller = new TrustController(mockHistoricalChartBuilder.Object, mockFinancialDataService.Object, mockFCService.Object, mockEdubaseDataService.Object, null, mockCookieManager.Object, mockTrustHistoryService.Object, mockGiasLookupService.Object, mockCscpLookupService.Object); controller.ControllerContext = new ControllerContext(rc, controller); var action = controller.Index(123); action.Wait(); Assert.IsInstanceOf(typeof(RedirectToRouteResult), action.Result); Assert.AreEqual("School", (action.Result as RedirectToRouteResult).RouteValues["Controller"]); Assert.AreEqual("Detail", (action.Result as RedirectToRouteResult).RouteValues["Action"]); }
/// <summary> /// Create a authorise token from the request. Returns the bdy html result. /// </summary> /// <param name="httpRequest">The current http request.</param> /// <param name="rawUri">A System.Uri object containing information regarding the URL of the current request.</param> /// <param name="queryString">The collection of HTTP query string variables.</param> /// <param name="form">The collection of form variables.</param> /// <param name="headers">The collection of HTTP headers.</param> /// <param name="cookies">The collection of cookies sent by the client.</param> /// <param name="returnType">The type of response to return.</param> /// <param name="responseHeaders">The response headers for the request.</param> /// <param name="isApprovedByUser">Has the user approved the client to access the resources.</param> /// <returns>The formatted redirect url; else null.</returns> private object CreateAuthorise(HttpRequestBase httpRequest, Uri rawUri, NameValueCollection queryString, NameValueCollection form, NameValueCollection headers, HttpCookieCollection cookies, int returnType, out System.Net.WebHeaderCollection responseHeaders, bool isApprovedByUser) { IDirectedProtocolMessage response = null; OutgoingWebResponse webResponse = null; string clientID = null; string nonce = null; string codeKey = null; try { // Make sure that all the passed parameters are valid. if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } if (rawUri == null) { throw new ArgumentNullException("rawUri"); } if (queryString == null) { throw new ArgumentNullException("queryString"); } if (form == null) { throw new ArgumentNullException("form"); } if (headers == null) { throw new ArgumentNullException("headers"); } if (cookies == null) { throw new ArgumentNullException("cookies"); } // Read the request make sure it is valid. EndUserAuthorizationRequest pendingRequest = _authorizationServer.ReadAuthorizationRequest(httpRequest); if (pendingRequest == null) { throw new Exception("Missing authorization request."); } // Only process if the user has approved the request. if (isApprovedByUser) { // Make sure all maditor parameters are present. _oAuthAuthorizationServer.ValidateAuthoriseRequestParametersAbsent(queryString); if (_oAuthAuthorizationServer.ParametersAbsent.Count() > 0) { throw new Exception("Some authorisation request parameters are missing."); } // Assign each query string parameter. clientID = pendingRequest.ClientIdentifier; string callback = pendingRequest.Callback.ToString(); string state = pendingRequest.ClientState; string scope = OAuthUtilities.JoinScopes(pendingRequest.Scope); string responseType = (pendingRequest.ResponseType == EndUserAuthorizationResponseType.AccessToken ? "token" : "code"); string companyUniqueUserID = queryString["com_unique_uid"]; // Set the crytography key store values. _authorizationServer.AuthorizationServerServices.CryptoKeyStore.ExpiryDateTime = DateTime.UtcNow.AddYears(1); _authorizationServer.AuthorizationServerServices.CryptoKeyStore.ClientIndetifier = clientID; _authorizationServer.AuthorizationServerServices.CryptoKeyStore.GetCodeKey = false; // Create a new nonce and store it in the nonce store. nonce = _nonceStore.GenerateNonce(); _nonceStore.StoreNonce(DateTime.UtcNow, nonce, clientID); // Create the access token from the stores, and create a new verification code. string verifier = _consumerStore.SetVerificationCode(clientID, nonce, companyUniqueUserID, scope); EndUserAuthorizationSuccessAccessTokenResponse successAccessTokenResponse = null; // Prepare the request. pass the nonce and join the userID and nonce of // the user that approved the resource access request. response = _authorizationServer.PrepareApproveAuthorizationRequest( pendingRequest, companyUniqueUserID + "_" + nonce, nonce, out successAccessTokenResponse); // Prepare the authorisation response. webResponse = _authorizationServer.Channel.PrepareResponse(response); // Create the query collection of the code request // and extract the code value that is to be sent // the the client. NameValueCollection queryResponseString = new NameValueCollection(); Uri uriRequest = webResponse.GetDirectUriRequest(_authorizationServer.Channel); // For each query item. string[] queries = uriRequest.Query.Split(new char[] { '&' }); foreach (string query in queries) { // Add the query name and value to the collection. string[] queriesNameValue = query.Split(new char[] { '=' }); queryResponseString.Add(queriesNameValue[0].TrimStart(new char[] { '?' }), queriesNameValue[1]); } // What type of response is to be handled. switch (pendingRequest.ResponseType) { case EndUserAuthorizationResponseType.AuthorizationCode: // The user has requested a code, this is // used so the client can get a token later. // If the code response type exits. if (queryResponseString["code"] != null) { codeKey = HttpUtility.UrlDecode(queryResponseString["code"]); } // Insert the code key (code or token); if (!String.IsNullOrEmpty(codeKey)) { _tokenStore.StoreCodeKey(clientID, nonce, codeKey); } break; case EndUserAuthorizationResponseType.AccessToken: // This is used so the client is approved and a token is sent back. // Update the access token. if (successAccessTokenResponse != null) { if (!String.IsNullOrEmpty(successAccessTokenResponse.AccessToken)) { _tokenStore.UpdateAccessToken(successAccessTokenResponse.AccessToken, nonce); } } break; } } else { // Send an error response. response = _authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest); } // What type should be returned. switch (returnType) { case 0: // A URI request redirect only. responseHeaders = webResponse.Headers; return(webResponse.GetDirectUriRequest(_authorizationServer.Channel)); case 1: // The complete html body. responseHeaders = webResponse.Headers; return(webResponse.Body); case 2: // The action result. responseHeaders = webResponse.Headers; return(webResponse.AsActionResult()); default: // Default is the complete html body. responseHeaders = webResponse.Headers; return(webResponse.Body); } } catch (Exception ex) { // Get the current token errors. responseHeaders = null; _tokenError = ex.Message; return(null); } }
/// <summary> /// Create a request token from the request. /// </summary> /// <param name="httpRequest">The current http request.</param> /// <param name="rawUri">A System.Uri object containing information regarding the URL of the current request.</param> /// <param name="queryString">The collection of HTTP query string variables.</param> /// <param name="form">The collection of form variables.</param> /// <param name="headers">The collection of HTTP headers.</param> /// <param name="cookies">The collection of cookies sent by the client.</param> /// <param name="responseHeaders">The response headers for the request.</param> /// <param name="returnType">The type of response to return.</param> /// <returns>The token if successful; else null.</returns> private object CreateToken(HttpRequestBase httpRequest, Uri rawUri, NameValueCollection queryString, NameValueCollection form, NameValueCollection headers, HttpCookieCollection cookies, out System.Net.WebHeaderCollection responseHeaders, int returnType) { OutgoingWebResponse outgoingWebResponse = null; AccessTokenSuccessResponse accessTokenSuccessResponse = null; IProtocolMessage message = null; string codeKey = null; string refreshToken = null; string clientID = null; string nonce = null; try { // Make sure that all the passed parameters are valid. if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } if (rawUri == null) { throw new ArgumentNullException("rawUri"); } if (queryString == null) { throw new ArgumentNullException("queryString"); } if (form == null) { throw new ArgumentNullException("form"); } if (headers == null) { throw new ArgumentNullException("headers"); } if (cookies == null) { throw new ArgumentNullException("cookies"); } // Set the crytography key store values. _authorizationServer.AuthorizationServerServices.CryptoKeyStore.ExpiryDateTime = DateTime.UtcNow.AddYears(1); _authorizationServer.AuthorizationServerServices.CryptoKeyStore.GetCodeKey = true; // Attempt to find the 'code' parameter in the form. IEnumerable <string> codeKeys = form.AllKeys.Where(u => u.EndsWith("code")); if (codeKeys == null || codeKeys.Count() < 1) { // Attempt to find the 'code' parameter in the query string. if (queryString != null || queryString.Keys.Count > 0) { if (queryString["code"] != null) { codeKey = queryString["code"]; } } } else { codeKey = form["code"]; } // If a code value exists. if (!String.IsNullOrEmpty(codeKey)) { // Get the nonce data for the code value. nonce = _tokenStore.GetNonce(codeKey); } // Attempt to find the 'refresh_token' parameter in the form. IEnumerable <string> refreshTokens = form.AllKeys.Where(u => u.EndsWith("refresh_token")); if (refreshTokens == null || refreshTokens.Count() < 1) { // Attempt to find the 'refresh_token' parameter in the query string. if (queryString != null || queryString.Keys.Count > 0) { if (queryString["refresh_token"] != null) { refreshToken = queryString["refresh_token"]; } } } else { refreshToken = form["refresh_token"]; } // Pass a refresh token if (!String.IsNullOrEmpty(refreshToken)) { string clientIdentifier = null; string clientSecret = null; // Get the refresh token data from the http request. _oAuthAuthorizationServer.GetRefreshTokenData(queryString, form, out clientIdentifier, out clientSecret); // Get the nonce data for the code value. nonce = _tokenStore.GetNonce(refreshToken, clientIdentifier, clientSecret); } // Handles an incoming request to the authorization server's token endpoint. message = _authorizationServer.HandleTokenRequest(nonce, out clientID, out accessTokenSuccessResponse, httpRequest); // Set the crytography key store values after finding the client identifier. _authorizationServer.AuthorizationServerServices.CryptoKeyStore.ClientIndetifier = clientID; // Handles an incoming request to the authorization server's token endpoint. outgoingWebResponse = _authorizationServer.HandleTokenRequestPrepareResponse(message); // Update the access token. if (accessTokenSuccessResponse != null) { if (!String.IsNullOrEmpty(accessTokenSuccessResponse.AccessToken)) { _tokenStore.UpdateAccessToken(accessTokenSuccessResponse.AccessToken, nonce, accessTokenSuccessResponse.RefreshToken); } } // What type should be returned. switch (returnType) { case 0: // The complete html body. responseHeaders = outgoingWebResponse.Headers; return(outgoingWebResponse.Body); case 1: // The action result. responseHeaders = outgoingWebResponse.Headers; return(outgoingWebResponse.AsActionResult()); default: // Default is html body. responseHeaders = outgoingWebResponse.Headers; return(outgoingWebResponse.Body); } } catch (Exception ex) { // Get the current token errors. responseHeaders = null; _tokenError = ex.Message; return(null); } }
/// <summary> /// Create a authorise token from the request. Returns the action result. /// </summary> /// <param name="httpRequest">The current http request.</param> /// <param name="rawUri">A System.Uri object containing information regarding the URL of the current request.</param> /// <param name="queryString">The collection of HTTP query string variables.</param> /// <param name="form">The collection of form variables.</param> /// <param name="headers">The collection of HTTP headers.</param> /// <param name="cookies">The collection of cookies sent by the client.</param> /// <param name="responseHeaders">The response headers for the request.</param> /// <param name="isApprovedByUser">Has the user approved the client to access the resources.</param> /// <returns>The formatted redirect url; else null.</returns> public ActionResult CreateAuthoriseActionResult(HttpRequestBase httpRequest, Uri rawUri, NameValueCollection queryString, NameValueCollection form, NameValueCollection headers, HttpCookieCollection cookies, out System.Net.WebHeaderCollection responseHeaders, bool isApprovedByUser = false) { object ret = CreateAuthorise(httpRequest, rawUri, queryString, form, headers, cookies, 2, out responseHeaders, isApprovedByUser); return((ActionResult)ret ?? null); }
/// <summary> /// Create a request token from the request. /// </summary> /// <param name="httpRequest">The current http request.</param> /// <param name="rawUri">A System.Uri object containing information regarding the URL of the current request.</param> /// <param name="queryString">The collection of HTTP query string variables.</param> /// <param name="form">The collection of form variables.</param> /// <param name="headers">The collection of HTTP headers.</param> /// <param name="cookies">The collection of cookies sent by the client.</param> /// <param name="responseHeaders">The response headers for the request.</param> /// <returns>The token if successful; else null.</returns> public ActionResult CreateTokenActionResult(HttpRequestBase httpRequest, Uri rawUri, NameValueCollection queryString, NameValueCollection form, NameValueCollection headers, HttpCookieCollection cookies, out System.Net.WebHeaderCollection responseHeaders) { object ret = CreateToken(httpRequest, rawUri, queryString, form, headers, cookies, out responseHeaders, 1); return((ActionResult)ret ?? null); }
/// <summary> /// /// </summary> /// <param name="httpMethod">Method like <c>POST</c>.</param> /// <param name="pathAndQuery">Absolute path and query string (if one exist)</param> /// <param name="httpVersion">HTTP version like <c>HTTP/1.1</c></param> public HttpRequest(string httpMethod, string pathAndQuery, string httpVersion) : base(httpMethod, pathAndQuery, httpVersion) { Form = new ParameterCollection(); Files = new HttpFileCollection(); Cookies = new HttpCookieCollection<IHttpCookie>(); }
internal void FillInCookiesCollection(HttpCookieCollection cookieCollection, bool includeResponse) { if (_wr == null) return; String s = _wr.GetKnownRequestHeader(HttpWorkerRequest.HeaderCookie); // Parse the cookie server variable. // Format: c1=k1=v1&k2=v2; c2=... int l = (s != null) ? s.Length : 0; int i = 0; int j; char ch; HttpCookie lastCookie = null; while (i < l) { // find next ';' (don't look to ',' as per 91884) j = i; while (j < l) { ch = s[j]; if (ch == ';') break; j++; } // create cookie form string String cookieString = s.Substring(i, j - i).Trim(); i = j + 1; // next cookie start if (cookieString.Length == 0) continue; HttpCookie cookie = CreateCookieFromString(cookieString); // some cookies starting with '$' are really attributes of the last cookie if (lastCookie != null) { String name = cookie.Name; // add known attribute to the last cookie (if any) if (name != null && name.Length > 0 && name[0] == '$') { if (StringUtil.EqualsIgnoreCase(name, "$Path")) lastCookie.Path = cookie.Value; else if (StringUtil.EqualsIgnoreCase(name, "$Domain")) lastCookie.Domain = cookie.Value; continue; } } // regular cookie cookieCollection.AddCookie(cookie, true); lastCookie = cookie; // goto next cookie } // Append response cookies if ((includeResponse) && (Response != null)) { HttpCookieCollection responseCookies = Response.Cookies; // if (responseCookies.Count > 0) { HttpCookie[] rcookies = new HttpCookie[responseCookies.Count]; responseCookies.CopyTo(rcookies, 0); for (int iCookie = 0; iCookie < rcookies.Length; iCookie++) cookieCollection.AddCookie(rcookies[iCookie], true); } } }
public ClientHandshake(string handshakeString) { Cookies = new HttpCookieCollection(); AdditionalFields = new Dictionary <string, string>(); // the "grammar" of the handshake var pattern = @"^(?<connect>[^\s]+)\s(?<path>[^\s]+)\sHTTP\/1\.1\r\n" + // request line @"((?<field_name>[^:\r\n]+):\s(?<field_value>[^\r\n]+)\r\n)+"; // unordered set of fields (name-chars colon space any-chars cr lf) // match the handshake against the "grammar" var regex = new Regex(pattern, RegexOptions.IgnoreCase); var match = regex.Match(handshakeString); var fields = match.Groups; // save the request path Uri.TryCreate(fields["path"].Value, UriKind.RelativeOrAbsolute, out _uri); // run through every match and save them in the handshake object for (int i = 0; i < fields["field_name"].Captures.Count; i++) { var name = fields["field_name"].Captures[i].ToString(); var value = fields["field_value"].Captures[i].ToString(); if (string.IsNullOrEmpty(value)) //discussion:244004 { continue; } switch (name.ToLowerInvariant()) { case "sec-websocket-key": Key = value; break; case "sec-websocket-version": Version = value; break; case "sec-websocket-protocol": SubProtocol = value; break; case "origin": Origin = value.ToLowerInvariant(); // to lower as per the protocol break; case "host": Host = value; break; case "sec-websocket-extensions": // TODO break; case "cookie": // create and fill a cookie collection from the data in the handshake var cookies = value.Split(';'); foreach (var item in cookies) { // the name if before the '=' char var c_name = item.Remove(item.IndexOf('=')); // the value is after var c_value = item.Substring(item.IndexOf('=') + 1); // put the cookie in the collection (this also parses the sub-values and such) Cookies.Add(new HttpCookie(c_name.TrimStart(), c_value)); } break; default: // some field that we don't know about AdditionalFields[name] = value; break; } } }
public static async Task <string> LoginBilibili(string UserName, string Password) { try { //https://api.bilibili.com/login?appkey=422fd9d7289a1dd9&platform=wp&pwd=JPJclVQpH4jwouRcSnngNnuPEq1S1rizxVJjLTg%2FtdqkKOizeIjS4CeRZsQg4%2F500Oye7IP4gWXhCRfHT6pDrboBNNkYywcrAhbOPtdx35ETcPfbjXNGSxteVDXw9Xq1ng0pcP1burNnAYtNRSayEKC1jiugi1LKyWbXpYE6VaM%3D&type=json&userid=xiaoyaocz&sign=74e4c872ec7b9d83d3a8a714e7e3b4b3 //发送第一次请求,得到access_key string url = "https://api.bilibili.com/login?appkey=422fd9d7289a1dd9&platform=wp&pwd=" + WebUtility.UrlEncode(await GetEncryptedPassword(Password)) + "&type=json&userid=" + WebUtility.UrlEncode(UserName); url += "&sign=" + ApiHelper.GetSign(url); string results = await WebClientClass.GetResults(new Uri(url)); //Json解析及数据判断 LoginModel model = new LoginModel(); model = JsonConvert.DeserializeObject <LoginModel>(results); if (model.code == -627) { return("登录失败,密码错误!"); } if (model.code == -626) { return("登录失败,账号不存在!"); } if (model.code == -625) { return("密码错误多次"); } if (model.code == -628) { return("未知错误"); } if (model.code == -1) { return("登录失败,程序注册失败!请联系作者!"); } Windows.Web.Http.HttpClient hc = new Windows.Web.Http.HttpClient(); if (model.code == 0) { access_key = model.access_key; Windows.Web.Http.HttpResponseMessage hr2 = await hc.GetAsync(new Uri("http://api.bilibili.com/login/sso?&access_key=" + model.access_key + "&appkey=422fd9d7289a1dd9&platform=wp")); hr2.EnsureSuccessStatusCode(); SettingHelper.AccessKey = model.access_key; } //看看存不存在Cookie HttpBaseProtocolFilter hb = new HttpBaseProtocolFilter(); HttpCookieCollection cookieCollection = hb.CookieManager.GetCookies(new Uri("http://bilibili.com/")); List <string> ls = new List <string>(); foreach (HttpCookie item in cookieCollection) { ls.Add(item.Name); } if (ls.Contains("DedeUserID")) { return("登录成功"); } else { return("登录失败"); } } catch (Exception ex) { if (ex.HResult == -2147012867) { return("登录失败,检查你的网络连接!"); } else { return("登录发生错误"); } } }
public FakeHttpContext(string relativeUrl, FakePrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems) { this.relativeUrl = relativeUrl; this.principal = principal; this.formParams = formParams; this.queryStringParams = queryStringParams; this.cookies = cookies; this.sessionItems = sessionItems; }
/// <summary> /// Initializes a new instance of the <see cref="HttpResponse"/> class. /// </summary> /// <param name="statusCode">The status code.</param> /// <param name="reasonPhrase">The reason phrase.</param> /// <param name="httpVersion">The HTTP version.</param> internal HttpResponse(int statusCode, string reasonPhrase, string httpVersion) : base(statusCode, reasonPhrase, httpVersion) { Cookies = new HttpCookieCollection<IResponseCookie>(); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { //此处理并非是客户端直接传递过来的参数,而是经过代码处理后的结果 RequestContext request = filterContext.RequestContext; HttpContextBase hcb = request.HttpContext; //HTTP请求相关参数 //是否开启日志记录 if (InitAppSetting.OpenDebugType) { StringBuilder sb = new StringBuilder(); HttpRequestBase req = hcb.Request;//包含请求头相关信息的实体 string webBrowser = req.UserAgent; sb.AppendLine("UserAgent=\t" + webBrowser); string[] userLanguage = req.UserLanguages;//用户使用的语言 sb.AppendLine("UserLanguages =\t" + string.Join("|", userLanguage)); string url = req.Url.ToString(); sb.AppendLine("Url=\t" + url); string method = req.RequestType;//HTTP请求形式 sb.AppendLine("RequestType=\t" + method); string httpMethod = req.HttpMethod; sb.AppendLine("HttpMethod=\t" + httpMethod); //req.Form //请求的表单 //req.Headers //请求头 HttpCookieCollection cookies = req.Cookies;//请求的cookie if (cookies.Count > 0) { sb.AppendLine("Cookies="); /* * “System.InvalidCastException”类型的异常在 HRApp.Web.dll 中发生,但未在用户代码中进行处理 * * 其他信息: 无法将类型为“System.String”的对象强制转换为类型“System.Web.HttpCookie” * 不能直接使用foreach * foreach (HttpCookie item in cookies) * { * sb.AppendLine(item.ConvertJson()+"\r\n"); * } * https://www.cnblogs.com/answercard/archive/2009/02/02/1382404.html */ for (int i = 0; i < cookies.Count; i++) { HttpCookie hc = cookies[i]; sb.AppendLine(hc.ConvertJson() + "\r\n"); } } string mimeType = req.ContentType;//文件传输类型 sb.AppendLine("ContentType=\t" + mimeType); System.Text.Encoding userEncoding = req.ContentEncoding; sb.AppendLine("ContentEncoding=\t" + userEncoding.ToString()); HttpBrowserCapabilitiesBase browserInfo = req.Browser; sb.AppendLine("Browser=\t" + browserInfo.Browser + "\t"); for (int i = 0; i < browserInfo.Browsers.Count; i++) { sb.Append(browserInfo.Browsers[i].ToString() + "\t"); } sb.AppendLine("\r\nMobileDeviceModel=\t" + browserInfo.MobileDeviceModel); sb.AppendLine("Platform=\t" + browserInfo.Platform); string[] browserSupperMimeType = req.AcceptTypes;//HTTP预返回前端支持的文件格式 sb.AppendLine("\nAcceptTypes=\t" + string.Join(" ", browserSupperMimeType)); sb.AppendLine("Ip:" + GetBrowserIp()); ELogType el = ELogType.DebugData; string file = LogPrepare.GetLogName(el); LoggerWriter.CreateLogFile(sb.ToString(), LogPrepare.GetLogPath(), el, file, true); } IDictionary <string, object> apiParamList = filterContext.ActionParameters;//进入接口传递的参数 RouteData rd = filterContext.RouteData; if (apiParamList.Count == 0) { return; } base.OnActionExecuting(filterContext); }
/// <summary> /// Initializes a new instance of the <see cref="CookieHeader"/> class. /// </summary> /// <param name="collection">The collection.</param> /// <exception cref="ArgumentNullException"><c>collection</c> is <c>null</c>.</exception> public CookieHeader(HttpCookieCollection collection) { if (collection == null) throw new ArgumentNullException("collection"); Cookies = collection; }
public FakeHttpContext(Uri url, string appRelativeUrl, string httpMethod, IPrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems) { _url = url; _appRelativeUrl = appRelativeUrl; _httpMethod = httpMethod; _principal = principal; _formParams = formParams; _queryStringParams = queryStringParams; _cookies = cookies; _sessionItems = sessionItems; if (principal != null) { _isAuthenticated = principal.Identity.IsAuthenticated; } _httpRequest = new FakeHttpRequest(_url, _appRelativeUrl, _httpMethod, _isAuthenticated, _formParams, _queryStringParams, _cookies, InputStream); _httpResponse = new FakeHttpResponse(); }
public static Cart GetCartFromCookie(HttpCookieCollection Cookies) { // If we have a cart cookie, try loading from the guid found in the cookie if (Cookies[Constants.CookieKeys.CURRENT_CART] != null && Cookies[Constants.CookieKeys.CURRENT_CART].Values.HasKeys()) { HttpCookie cart_cookie = Cookies[Constants.CookieKeys.CURRENT_CART]; string cart_id = cart_cookie.Values.Get("cart_id"); string guid_id = cart_cookie.Values.Get("guid_id"); Cart cart = Cart.GetCartByGuid(new Guid(guid_id)); if (cart != null && cart.IsLoaded && cart.CartId.ToString() == cart_id) { return cart; } } throw new CartException("No Cart Cookie Found"); }
// Methods public FakeHttpRequest(Uri url, string appRelativeUrl, string httpMethod, bool isAuthenticated, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies) { if (!(string.IsNullOrEmpty(appRelativeUrl) || appRelativeUrl.StartsWith("~"))) { throw new Exception("appRelativeUrl must start with ~"); } this._url = url; this._appRelativeUrl = appRelativeUrl; this._httpMethod = httpMethod; this._isAuthenticated = isAuthenticated; this._formParams = formParams; this._queryStringParams = queryStringParams; this._cookies = cookies; }
/// <summary> /// Will mock the user information for the current request /// </summary> /// <param name="controller">Controller to add user information to</param> /// <param name="user">Data representing logged in user</param> /// <param name="requestFormValues">Data to be returned by Request.Form</param> public static void SetupControllerContext(Controller controller, User user, NameValueCollection requestFormValues = null) { controller.Should().Not.Be.Null(); if (user == null) { user = new User { Username = string.Empty } } ; var identity = new GenericIdentity(user.Username); var principal = new UserPrincipal(user, identity); var httpContext = new Mock <HttpContextBase>(); var request = new Mock <HttpRequestBase>(); var cookies = new HttpCookieCollection(); request.Setup(x => x.Cookies).Returns(cookies); request.Setup(x => x.ApplicationPath).Returns("/"); request.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns("~/"); request.Setup(x => x.PathInfo).Returns(string.Empty); request.Setup(x => x.Form).Returns(requestFormValues); request.Setup(x => x.Headers).Returns(new NameValueCollection()); var response = new Mock <HttpResponseBase>(); response.Setup(x => x.Cookies).Returns(cookies); response.Setup(x => x.SetCookie(It.IsAny <HttpCookie>())).Callback <HttpCookie>(x => cookies.Add(x)); response.Setup(x => x.ApplyAppPathModifier(It.IsAny <string>())).Returns((string virtualPath) => virtualPath); var server = new Mock <HttpServerUtilityBase>(); var tempPath = Path.GetTempPath(); server.Setup(x => x.MapPath(It.IsAny <string>())).Returns((string input) => { var value = input; if (input.StartsWith("~")) { value = value.Substring(1); } if (value.StartsWith("/")) { value = value.Substring(1); } return(Path.Combine(tempPath, value)); }); response.Setup(x => x.Headers).Returns(new NameValueCollection()); response.SetupProperty(x => x.StatusCode); response.Setup(x => x.AddHeader(It.IsAny <string>(), It.IsAny <string>())).Callback((string s1, string s2) => response.Object.Headers.Add(s1, s2)); httpContext.Setup(x => x.User).Returns(principal); httpContext.Setup(x => x.Request).Returns(request.Object); httpContext.Setup(x => x.Response).Returns(response.Object); httpContext.Setup(x => x.Server).Returns(server.Object); var mockContext = new Mock <ControllerContext>(); mockContext.Setup(x => x.HttpContext).Returns(httpContext.Object); //Create old HttpContext.Current that's used outside of controllers, so we can get the user HttpContext.Current = new HttpContext( new HttpRequest("", "http://tempuri.org", ""), new HttpResponse(new StringWriter()) ) { User = principal }; controller.ControllerContext = mockContext.Object; var urlHelper = new UrlHelper(new RequestContext(httpContext.Object, new RouteData()), RouteTable.Routes); controller.Url = urlHelper; }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // Adding meta Discription HtmlMeta objMeta = new HtmlMeta(); objMeta.Name = "Description"; objMeta.Content = WebConfig.GetValues("MetaDiscription"); this.Header.Controls.Add(objMeta); // Adding meta KeyWords objMeta = new HtmlMeta(); objMeta.Name = "keywords"; objMeta.Content = WebConfig.GetValues("MetaKeword"); this.Header.Controls.Add(objMeta); HttpCookieCollection objHttpCookieCollection = Request.Cookies; HttpCookie objHttpCookie = objHttpCookieCollection.Get("MatCookie5639sb"); if (Crypto.DeCrypto(objHttpCookie.Values["UserType"]) == "PaidMember") { RB_H_yes.Enabled = true; TB_Password.TextMode = TextBoxMode.Password; TB_Password.Text = ""; TB_Password_C.TextMode = TextBoxMode.Password; TB_Password_C.Text = ""; } if (MatrimonialAlbumManager.IsImageExists(Crypto.DeCrypto(objHttpCookie.Values["ApplicationID"]), MatrimonialAlbumManager.ImageType.Horoscope)) { HL_Delete.Visible = true; } } else//postback { /// ///upload image /// FileInfo imageInfo = new FileInfo(File_Image.Value.Trim()); if (!imageInfo.Exists) { RegisterClientScriptBlock("alertMsg", "<script>alert('please select one image file.');</script>"); } else { switch (imageInfo.Extension.ToUpper()) { case ".JPG": if (UpLoadImageFile(imageInfo)) { L_State.Text = "Horoscope sucessfully inserted"; HL_Delete.Visible = true; } else { L_State.Text = "Error in Saving your file"; HL_Delete.Visible = true; } break; case ".GIF": if (UpLoadImageFile(imageInfo)) { L_State.Text = "Horoscope sucessfully inserted"; HL_Delete.Visible = true; } else { L_State.Text = "Error in Saving your file"; } break; case ".BMP": if (UpLoadImageFile(imageInfo)) { L_State.Text = "Horoscope sucessfully inserted"; HL_Delete.Visible = true; } else { L_State.Text = "Error in Saving your file"; } break; default: RegisterClientScriptBlock("alertMsg", "<script>alert('Use either images suchus bmp,jpg,gif');</script>"); break; } } } }
private static HttpContextBase CreateContext(string cookieValue = null, string formValue = null, string username = "******") { HttpCookieCollection requestCookies = new HttpCookieCollection(); if (!String.IsNullOrEmpty(cookieValue)) { requestCookies.Set(new HttpCookie(_antiForgeryTokenCookieName, cookieValue)); } NameValueCollection formCollection = new NameValueCollection(); if (!String.IsNullOrEmpty(formValue)) { formCollection.Set(AntiForgeryData.GetAntiForgeryTokenName(null), formValue); } Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>(); mockContext.Setup(c => c.Request.ApplicationPath).Returns("/SomeAppPath"); mockContext.Setup(c => c.Request.Cookies).Returns(requestCookies); mockContext.Setup(c => c.Request.Form).Returns(formCollection); mockContext.Setup(c => c.Response.Cookies).Returns(new HttpCookieCollection()); mockContext.Setup(c => c.User.Identity.IsAuthenticated).Returns(true); mockContext.Setup(c => c.User.Identity.Name).Returns(username); return mockContext.Object; }
private bool UpLoadImageFile(FileInfo info) { /* * UserAlbum_UpdateHoroscope * UserAlbum_InsertImage * * @ApplicationID varchar(15) * @Horoscope image * @HoroPassword Varchar(25) */ try { /// /// striming image /// byte[] byteContent = new byte[info.Length]; FileStream objFileStream = info.OpenRead(); objFileStream.Read(byteContent, 0, byteContent.Length); objFileStream.Close(); /// /// Processing image /// byteContent = EditImage.GetThumbNail(byteContent, 600, 600, true); byteContent = EditImage.SetWatermark(byteContent, WebConfig.GetValues("FName"), 50, true, 36); /// /// DataBase operation starts /// HttpCookieCollection objHttpCookieCollection = Request.Cookies; HttpCookie objHttpCookie = objHttpCookieCollection.Get("MatCookie5639sb"); string strApplicationID = Crypto.DeCrypto(objHttpCookie.Values["ApplicationID"]); using (SqlConnection objConnection = DBConnection.GetSqlConnection()) { SqlCommand objCommand = new SqlCommand("UserAlbum_InsertImage", objConnection); if (MatrimonialAlbumManager.IsAlbumExists(strApplicationID)) { objCommand = new SqlCommand("UserAlbum_UpdateHoroscope", objConnection); } objCommand.CommandType = CommandType.StoredProcedure; /// Inserting parameters objCommand.Parameters.Add(new SqlParameter("@ApplicationID", SqlDbType.VarChar)); objCommand.Parameters["@ApplicationID"].Value = strApplicationID; objCommand.Parameters.Add(new SqlParameter("@Horoscope", SqlDbType.Image)); objCommand.Parameters["@Horoscope"].Value = byteContent; if (!RB_H_No.Checked) { objCommand.Parameters.Add(new SqlParameter("@HoroPassword", SqlDbType.VarChar)); objCommand.Parameters["@HoroPassword"].Value = TB_Password.Text; } /// Execute Sql Query objConnection.Open(); objCommand.ExecuteNonQuery(); objConnection.Close(); } return(true); } catch (Exception ex) { // ErrorLog return(false); } }
/// <summary> /// Parse cookie string /// </summary> /// <returns>A generated cookie collection.</returns> public IHttpCookieCollection<IHttpCookie> Parse(string value) { if (value == null) throw new ArgumentNullException("value"); _headerValue = value; _cookies = new HttpCookieCollection<IHttpCookie>(); _parserMethod = Name_Before; while (!IsEOF) { _parserMethod(); } OnCookie(_cookieName, _cookieValue); return _cookies; }
/// <summary> /// Parse cookie string /// </summary> /// <returns>A generated cookie collection.</returns> public IHttpCookieCollection<IHttpCookie> Parse() { _cookies = new HttpCookieCollection<IHttpCookie>(); _parserMethod = Name_Before; while (!IsEOF) { _parserMethod(); } OnCookie(_cookieName, _cookieValue); return _cookies; }
private static void ValidateCookieCollection(HttpCookieCollection cc) { int c = cc.Count; for (int i = 0; i < c; i++) { String key = cc.GetKey(i); String val = cc.Get(i).Value; if (!String.IsNullOrEmpty(val)) ValidateString(val, key, "Request.Cookies"); } }
private static void AssertSecure(string requestUrl, bool passwordExists, bool temporaryPasswordExists, string expectedUrl) { // Arrange var vpp = new Mock<VirtualPathProvider>(); if (temporaryPasswordExists) { vpp.Setup(m => m.FileExists("~/App_Data/Admin/_Password.config")).Returns(true); } if (passwordExists) { vpp.Setup(m => m.FileExists("~/App_Data/Admin/Password.config")).Returns(true); } string redirectUrl = null; var response = new Mock<HttpResponseBase>(); response.Setup(m => m.Redirect(It.IsAny<string>())).Callback<string>(url => redirectUrl = url); var request = new Mock<HttpRequestBase>(); request.Setup(m => m.QueryString).Returns(new NameValueCollection()); request.Setup(m => m.RawUrl).Returns(requestUrl); var cookies = new HttpCookieCollection(); request.Setup(m => m.Cookies).Returns(cookies); var context = new Mock<HttpContextBase>(); context.Setup(m => m.Request).Returns(request.Object); context.Setup(m => m.Response).Returns(response.Object); var startPage = new Mock<StartPage>() { CallBase = true }; var page = new Mock<WebPageRenderingBase>(); page.Setup(m => m.VirtualPath).Returns(requestUrl); startPage.Object.ChildPage = page.Object; page.Setup(m => m.Context).Returns(context.Object); // Act AdminSecurity.Authorize(startPage.Object, vpp.Object, MakeAppRelative); // Assert Assert.Equal(expectedUrl, redirectUrl); }
public FakeHttpContext(string relativeUrl, string method, IPrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems) { this._relativeUrl = relativeUrl; this._method = method; this._principal = principal; this._formParams = formParams; this._queryStringParams = queryStringParams; this._cookies = cookies; this._sessionItems = sessionItems; this._items = new Dictionary <object, object>(); }
public FakeHttpRequest(HttpRequest httpRequest, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, RequestData data, HttpBrowserCapabilitiesData dataCaps) { _httpRequest = httpRequest; _formParams = formParams; _queryStringParams = queryStringParams; _cookies = cookies; _data = data; _dataCaps = dataCaps; _serverVariables = new NameValueCollection(); }
public void PersistFilterAddsDictionaryEntriesToCookie() { // Arrange var cookies = new HttpCookieCollection(); var response = new Mock<HttpResponseBase>(); response.Setup(c => c.Cookies).Returns(cookies); // Act PageUtils.PersistFilter(response.Object, "my-cookie", new Dictionary<string, string>() { { "a", "b" }, { "x", "y" } }); // Assert var cookie = cookies["my-cookie"]; Assert.Equal(cookie["a"], "b"); Assert.Equal(cookie["x"], "y"); }
public MockHttpContext() // constructor that initializes objects needed { cookies = new HttpCookieCollection(); // initializes cookie collection this.request = new MockRequest(cookies); // collection of cookies is injected this.response = new MockResponse(cookies); }
public FakeControllerContext(ControllerBase controller, HttpCookieCollection cookies) : this(controller, null, null, null, null, cookies, null) { }
public void ExtendQueueCookie_CookieExist_Test() { var eventId = "event1"; var secretKey = "4e1db821-a825-49da-acd0-5d376f2068db"; var queueId = "f8757c2d-34c2-4639-bef2-1736cdd30bbb"; var cookieKey = UserInQueueStateCookieRepository.GetCookieKey(eventId); var fakeContext = MockRepository.GenerateMock <HttpContextBase>(); var issueTime = DateTimeHelper.GetUnixTimeStampFromDate(DateTime.UtcNow.AddMinutes(-1)); var hash = QueueITTokenGenerator.GetSHA256Hash(eventId.ToLower() + queueId + "3" + "idle" + issueTime.ToString(), secretKey); var cookieValue = $"EventId={eventId}&QueueId={queueId}&{_FixedCookieValidityMinutesKey}=3&RedirectType=idle&IssueTime={issueTime}&Hash={hash}"; var fakeRequest = MockRepository.GenerateMock <HttpRequestBase>(); fakeContext.Stub(stub => stub.Request).Return(fakeRequest); var cookies = new HttpCookieCollection() { new HttpCookie("key1") { Value = "test" }, new HttpCookie("a") { Value = "test" }, new HttpCookie("b") { Value = "test" }, new HttpCookie(cookieKey) { Value = cookieValue, Domain = "testdomain" } }; fakeRequest.Stub(stub => stub.Cookies).Return(cookies); var fakeResponse = MockRepository.GenerateMock <HttpResponseBase>(); fakeContext.Stub(stub => stub.Response).Return(fakeResponse); fakeResponse.Stub(stub => stub.Cookies).Return(cookies); var testObject = new UserInQueueStateCookieRepository(fakeContext); testObject.ReissueQueueCookie(eventId, 12, secretKey); var newIssueTime = DateTimeHelper.GetDateTimeFromUnixTimeStamp(CookieHelper.ToNameValueCollectionFromValue(cookies[cookieKey].Value)["IssueTime"]); Assert.True(newIssueTime.Subtract(DateTime.UtcNow) < TimeSpan.FromSeconds(2)); Assert.True(cookies[cookieKey].Domain == "testdomain"); var state = testObject.GetState(eventId, 5, secretKey); Assert.True(state.IsValid); Assert.True(!state.IsStateExtendable); Assert.True(state.QueueId == queueId); Assert.True(state.RedirectType == "idle"); }
public void PersistFilterUsesExistingCookie() { // Arrange var cookieName = "my-cookie"; var cookies = new HttpCookieCollection(); cookies.Add(new HttpCookie(cookieName)); var response = new Mock<HttpResponseBase>(); response.Setup(c => c.Cookies).Returns(cookies); // Act PageUtils.PersistFilter(response.Object, "my-cookie", new Dictionary<string, string>()); // Assert Assert.Equal(1, cookies.Count); }
public ICatalogClient Create(HttpCookieCollection cookies, string catalogUrl) { return(new CatalogClient(cookies, catalogUrl)); }
private static HtmlHelper GetHtmlHelperForAntiForgeryToken(string cookieValue) { HttpCookieCollection requestCookies = new HttpCookieCollection(); HttpCookieCollection responseCookies = new HttpCookieCollection(); if (!String.IsNullOrEmpty(cookieValue)) { requestCookies.Set(new HttpCookie(AntiForgeryData.GetAntiForgeryTokenName("/SomeAppPath"), cookieValue)); } Mock<ViewContext> mockViewContext = new Mock<ViewContext>(); mockViewContext.Expect(c => c.HttpContext.Request.Cookies).Returns(requestCookies); mockViewContext.Expect(c => c.HttpContext.Request.ApplicationPath).Returns("/SomeAppPath"); mockViewContext.Expect(c => c.HttpContext.Response.Cookies).Returns(responseCookies); return new HtmlHelper(mockViewContext.Object, new Mock<IViewDataContainer>().Object) { Serializer = new SubclassedAntiForgeryTokenSerializer() }; }
public MockResponse(HttpCookieCollection cookies) { this.cookies = cookies; }
public void IsAuthenticatedReturnsTrueIfAuthCookieIsValid() { // Arrange var mockRequest = new Mock<HttpRequestBase>(); var cookies = new HttpCookieCollection(); mockRequest.Setup(m => m.Cookies).Returns(cookies); cookies.Add(AdminSecurity.GetAuthCookie()); // Act bool authorized = AdminSecurity.IsAuthenticated(mockRequest.Object); // Assert Assert.True(authorized); }
public MockRequest(HttpCookieCollection cookies) { this.cookies = cookies; }
public FakeHttpResponse() { this._cookies = new HttpCookieCollection(); }
public MockHttpContext() { cookies = new HttpCookieCollection(); this.request = new MockRequest(cookies); this.response = new MockResponse(cookies); }
public void IsAuthenticatedReturnsFalseIfAuthCookieInCollectionAndIsNotAValidAdminAuthCookie() { // Arrange var mockRequest = new Mock<HttpRequestBase>(); var cookies = new HttpCookieCollection(); mockRequest.Setup(m => m.Cookies).Returns(cookies); cookies.Add(new HttpCookie(".ASPXADMINAUTH", "test")); // Act bool authorized = AdminSecurity.IsAuthenticated(mockRequest.Object); // Assert Assert.False(authorized); }
protected string DetermineDesiredImage(HttpCookieCollection cookies) { int width = cookies["RIWidth"] == null ? int.MaxValue : int.Parse(cookies["RIWidth"].Value); int height = cookies["RIHeight"] == null ? int.MaxValue : int.Parse(cookies["RIHeight"].Value); short? battery = cookies["RIBattery"] == null ? (short?)null : short.Parse(cookies["RIBattery"].Value); double? bandwidth = cookies["RIBandwidth"] == null ? (int?)null : short.Parse(cookies["RIBandwidth"].Value); int maxSize = int.MaxValue; if ((battery.HasValue && battery == 0) || (bandwidth.HasValue && bandwidth < 0.6)) { maxSize = 800; } if (bandwidth.HasValue && bandwidth < 1.5) { maxSize = 1500; } if (width > maxSize || height > maxSize) { if (width > height) { height = maxSize / (width / height); width = maxSize; } else { width = maxSize / (height / width); height = maxSize; } } // get the directory base on the size return FindTheAvailableMapResolution(width, height) ?? DefaultImageFolder; }