public static string GetAuthorizationCookie(HttpCookieCollection cookies, string code, IBaseDb db) { //var code = request.QueryString["code"]; var stream = HttpTools.PostStream("https://oauth.yandex.ru/token", string.Format("grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}", code, ClientId, Password)); var model = SerializeTools.Deserialize <TokenModel>(stream); var userCookie = new HttpCookie("yandex_token") { Value = model.access_token, Expires = DateTime.Now.AddDays(30) }; stream = HttpTools.PostStream(InfoUrl, string.Format("oauth_token={0}", userCookie.Value)); var email = SerializeTools.Deserialize <UserModel>(stream).default_email; var user = db.SingleOrDefault <User>(u => u.Email == email); cookies.Set(userCookie); var rolesCookie = new HttpCookie("roles") { Value = string.Join(",", user.UserRoles.Select(r => r.Code)), Expires = DateTime.Now.AddDays(30) }; cookies.Set(rolesCookie); return(model.access_token); }
public static void SetSubCookie(string strCookieDomainName, string strGroupName, string strKey, string strValue, bool isHttpOnly) { HttpCookieCollection cookies = HttpContext.Current.Response.Cookies; HttpCookie httpCookie; if (cookies[strGroupName] == null) { httpCookie = new HttpCookie(strGroupName); if (!string.IsNullOrEmpty(strCookieDomainName)) { httpCookie.Domain = strCookieDomainName; } httpCookie.Path = "/"; httpCookie.HttpOnly = isHttpOnly; httpCookie.Values.Set(strKey, strValue); cookies.Set(httpCookie); return; } httpCookie = cookies.Get(strGroupName); if (!string.IsNullOrEmpty(strCookieDomainName)) { httpCookie.Domain = strCookieDomainName; } httpCookie.Path = "/"; httpCookie.HttpOnly = isHttpOnly; httpCookie.Values.Set(strKey, strValue); cookies.Set(httpCookie); }
public void Test_ReturnsSuccessIfValidCookieEsists() { var serializer = new TicketSerializer(); var ticket = new AuthenticationTicket( new ClaimsPrincipal( new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "Foo User"), }, AuthConstants.SPNEGO_DEFAULT_SCHEME)), AuthConstants.SPNEGO_DEFAULT_SCHEME); var serializedTicket = serializer.Serialize(ticket); var protectedTicket = dataProtector.Protect(serializedTicket); var encodedTicket = Convert.ToBase64String(protectedTicket); var cookie = new HttpCookie(AuthConstants.AUTH_COOKIE_NM) { Expires = DateTime.Now.AddDays(CookieAuthenticator.COOKIE_TIMEOUT_IN_MINUTES), Value = encodedTicket }; cookies.Set(cookie); browser.SetupGet(b => b.Cookies).Returns(true); var authenticator = new CookieAuthenticator(dataProtector, logger.Object); var result = authenticator.Authenticate(context.Object); Assert.True(result.Succeeded); Assert.Equal("Foo User", result.Principal.Identity.Name); }
public void addCookie(HttpCookieCollection c) { for (int i = 0; i < c.Count; i++) { cookies.Remove(c[i].Name); cookies.Set(c[i]); } }
public void DuplicateNames() { HttpCookieCollection col = new HttpCookieCollection(); HttpCookie cookie1 = new HttpCookie("cookie", "value1"); HttpCookie cookie2 = new HttpCookie("cookie", "value2"); col.Add(cookie1); col.Add(cookie2); Assert.AreEqual("value1", col["cookie"].Value, "add should use first used cookie"); col.Set(cookie2); Assert.AreEqual("value2", col["cookie"].Value, "set should use last used cookie"); col.Clear(); col.Add(cookie1); col.Add(cookie2); // Bug #553150 HttpCookie tmp = col.Get(0); Assert.AreEqual("cookie", tmp.Name, "#A1"); Assert.AreEqual("value1", tmp.Value, "#A1-1"); tmp = col.Get(1); Assert.AreEqual("cookie", tmp.Name, "#A2"); Assert.AreEqual("value2", tmp.Value, "#A2-1"); }
/// <summary> /// Sets a cookie used during authentication to store such parameters like current provider, state, nonce. /// </summary> /// <param name="cookieKey">The cookie's key.</param> /// <param name="cookieValue">The cookie's value.</param> /// <param name="shortLiving">True if the cookie should have short life time, False otherwise.</param> /// <remarks>The cookie is Http one and has an expiration 5 minutes.</remarks> public static void SetCustomCookie(string cookieKey, string cookieValue, bool shortLiving = true) { const int OneWeekMinutes = 10080; HttpCookieCollection cookies = HttpContext.Current.Response.Cookies; HttpCookie newCookie = new HttpCookie(cookieKey, cookieValue) { HttpOnly = true, Secure = true, Expires = DateTime.UtcNow.AddMinutes(shortLiving ? 5 : OneWeekMinutes) }; bool providerTypeCookieSet = false; foreach (string cookieName in cookies.AllKeys) { if (cookieName == cookieKey) { cookies.Set(newCookie); providerTypeCookieSet = true; break; } } if (!providerTypeCookieSet) { cookies.Add(newCookie); } }
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); }
internal override void WriteInternal(byte[] value, string name, string path, string domain, DateTime expirationTime, bool secure, bool httpOnly, HttpCookieCollection requestCookies, HttpCookieCollection responseCookies) { string cookieValue = Convert.ToBase64String(value); this.DeleteInternal(name, path, domain, requestCookies, responseCookies); foreach (KeyValuePair <string, string> current in this.GetCookieChunks(name, cookieValue)) { HttpCookie httpCookie = new HttpCookie(current.Key, current.Value); httpCookie.Secure = true; httpCookie.HttpOnly = httpOnly; httpCookie.Path = path; if (!string.IsNullOrEmpty(domain)) { httpCookie.Domain = domain; } if (expirationTime != DateTime.MinValue) { httpCookie.Expires = expirationTime; } responseCookies.Set(httpCookie); //if (DiagnosticUtility.ShouldTrace(TraceEventType.Information)) //{ // TraceEventType arg_A6_0 = TraceEventType.Information; // int arg_A6_1 = 786438; // string arg_A6_2 = null; // ChunkedCookieHandlerTraceRecord.Action arg_A0_0 = ChunkedCookieHandlerTraceRecord.Action.Writing; // HttpCookie expr_9A = httpCookie; // TraceUtility.TraceEvent(arg_A6_0, arg_A6_1, arg_A6_2, new ChunkedCookieHandlerTraceRecord(arg_A0_0, expr_9A, expr_9A.Path), null); //} } }
public static void Update(HttpCookieCollection cookies, SerializableCookie[] serializableCookies) { cookies.Clear(); foreach (var cookie in serializableCookies) { cookies.Set(cookie); } }
public static void SaveInResponseCookie(this HttpCookieCollection cookies, string accessToken, string refreshToken, string loggedInUserId) { var accessCookie = new HttpCookie(AuthoriseBaseAttribute.ACCESSTOKEN, accessToken); accessCookie.Expires = DateTime.Now.AddMinutes(Setup.TokenExpireMinutes); cookies.Set(accessCookie); var refreshCookie = new HttpCookie(AuthoriseBaseAttribute.REFRESHTOKEN, refreshToken); refreshCookie.Expires = DateTime.Now.AddMinutes(Setup.TokenExpireMinutes); cookies.Set(refreshCookie); var loggedUserCookie = new HttpCookie(AuthoriseBaseAttribute.CURRENT_USERID, loggedInUserId); loggedUserCookie.Expires = DateTime.Now.AddMinutes(Setup.TokenExpireMinutes); cookies.Set(loggedUserCookie); }
// todo [Test] // public void Ресетит_куки_если_не_aутентифицировался() // { // _httpRequest.SetupGet(request => request.Url).Returns(new Uri("https://www.mysite.com:444/")); // // var agent = new Mock<Agent>(); // agent.Setup(a => a.GetOrderedArray("com.sun.identity.agents.config.agent.logout.url")) // .Returns(new[] {"https://www.mysite.com:444/"}); // agent.Setup(a => a.GetFirst("com.sun.identity.agents.config.logout.redirect.url")) // .Returns("https://www.mysite.com:444/logoff"); // agent.Setup(a => a.GetOrderedArray("com.sun.identity.agents.config.logout.cookie.reset")).Returns(new[] {"test"}); // agent.Setup(a => a.GetSingle("com.sun.identity.agents.config.agenturi.prefix")) // .Returns("http://ibank.staging.rapidsoft.ru:80/"); // var module = new iis7AgentModule(agent.Object); // module.OnAuthentication(_httpContext.Object); // // _httpResponse.Verify(response => response.Redirect("https://www.mysite.com:444/logoff")); // _httpResponse.Verify(r => r.AddHeader("Set-Cookie", "test")); // } private void Login() { var cookieCollection = new HttpCookieCollection(); var sid = Auth.login("/clients", indexType.service, "ldap", new Callback[] { new NameCallback("11111111111"), new PasswordCallback("1111111111") }).token.sid; cookieCollection.Set(new HttpCookie("svbid", sid)); _httpRequest.SetupGet(r => r.Cookies).Returns(cookieCollection); _httpRequest.SetupGet(r => r.HttpMethod).Returns("GET"); }
public static void Set(this HttpCookieCollection cookies, string name, string value, DateTime expires, bool encode = true) { value = encode ? HttpUtility.UrlEncode(value) : value; cookies.Set( new HttpCookie(name, value) { Expires = expires } ); }
private void Page_Load(Object sender, EventArgs e) { HttpCookieCollection MyCookieCollection = Response.Cookies; // <Snippet1> MyCookie.Value = DateTime.Now.ToString(); MyCookieCollection.Set(MyCookie); // </Snippet1> }
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); }
/// <summary> /// 更新cookie /// </summary> /// <param name="cookie_name"></param> /// <param name="cookie_value"></param> /// <param name="cookies"></param> 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); }
private static void SetPreferredCulture(HttpCookieCollection cookies, string cultureName) { var cookie = new HttpCookie(CookieName, cultureName) { Expires = DateTime.Now.AddDays(30) }; cookies.Set(cookie); Debug.WriteLine("SetPreferredCulture: " + cultureName); }
private void Page_Load(Object sender, EventArgs e) { // <Snippet1> HttpCookieCollection MyCookieCollection = Request.Cookies; HttpCookie MyCookie = MyCookieCollection.Get("LastVisit"); MyCookie.Value = DateTime.Now.ToString(); MyCookieCollection.Set(MyCookie); // </Snippet1> }
public void Test_UsesCookieAuthenticator_ToSet_UserPrincipal_IfCookieAuthenticatorReturnsSuccess() { var serializer = new TicketSerializer(); var ticket = new AuthenticationTicket( new ClaimsPrincipal( new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "Foo User"), }, AuthConstants.SPNEGO_DEFAULT_SCHEME)), AuthConstants.SPNEGO_DEFAULT_SCHEME); var encodedTicket = Convert.ToBase64String(serializer.Serialize(ticket)); var cookie = new HttpCookie(AuthConstants.AUTH_COOKIE_NM) { Expires = DateTime.Now.AddDays(1), Value = encodedTicket }; cookies.Set(cookie); cookieAuthenticator.Setup(ca => ca.Authenticate(context.Object)).Returns(AuthenticateResult.Success(ticket)); var whitelistPath = "/whitelistpath"; var mockConfiguration = new Dictionary <string, string>() { { AuthConstants.WHITELIST_PATHS_CSV_NM, whitelistPath } }; request.SetupGet(r => r.Path).Returns("/anypath"); context.SetupGet(c => c.User).Returns(() => { return(null); }); var handler = new WindowsAuthenticationHandler(cookieAuthenticator.Object, spnegoAuthenticator.Object, GetConfiguration(), logger.Object); handler.HandleRequest(context.Object); spnegoAuthenticator.Verify(sa => sa.Authenticate(context.Object), Times.Never); spnegoAuthenticator.Verify(sa => sa.Challenge(It.IsAny <AuthenticationProperties>(), context.Object), Times.Never); cookieAuthenticator.Verify(ca => ca.SignIn(It.IsAny <AuthenticateResult>(), context.Object), Times.Never); context.VerifySet(c => c.User = ticket.Principal, Times.Once); }
public static void SetCookie(string strCookieDomainName, string strKey, string strValue, bool isHttpOnly) { HttpCookieCollection cookies = HttpContext.Current.Response.Cookies; HttpCookie httpCookie = new HttpCookie(strKey, strValue); if (!string.IsNullOrEmpty(strCookieDomainName)) { httpCookie.Domain = strCookieDomainName; } httpCookie.Path = "/"; httpCookie.HttpOnly = isHttpOnly; cookies.Set(httpCookie); }
public void AddCookies(List <string> aCookies, Uri aUri) { HttpCookie lCookie; for (int i = 0; i < aCookies.Count; i++) { lCookie = CreateCookie(aCookies[i], aUri); if (Validate(lCookie)) { mCookieCollection.Set(lCookie); } } }
public static void RemoveCookie(string strCookieDomainName, string strKey) { HttpCookieCollection cookies = HttpContext.Current.Response.Cookies; HttpCookie httpCookie = new HttpCookie(strKey, null); if (!string.IsNullOrEmpty(strCookieDomainName)) { httpCookie.Domain = strCookieDomainName; } httpCookie.Path = "/"; httpCookie.Expires = DateTime.MinValue; cookies.Set(httpCookie); }
private static void SetCookie(string name, string val) { HttpCookieCollection cookies = HttpContext.Current.Request.Cookies; HttpCookie cookie = cookies[name]; if (cookie == null) { cookie = new HttpCookie(name); cookies.Add(cookie); } cookie.Value = val; cookies.Set(cookie); }
public void Deny_Unrestricted() { HttpCookieCollection jar = new HttpCookieCollection(); jar.Add(biscuit); jar.CopyTo(new object[1], 0); Assert.IsNull(jar.GetKey(0), "GetKey"); jar.Remove("chocolat"); jar.Set(biscuit); Assert.IsNotNull(jar.Get(0), "Get(int)"); Assert.IsNull(jar.Get("chocolat"), "Get(string)"); Assert.IsNotNull(jar[0], "this[int]"); Assert.IsNull(jar["chocolat"], "this[string]"); Assert.AreEqual(1, jar.AllKeys.Length, "AllKeys"); jar.Clear(); }
private void Page_Load(Object sender, EventArgs e) { // <Snippet1> int loop1; HttpCookieCollection MyCookieCollection = Response.Cookies; for (loop1 = 0; loop1 < MyCookieCollection.Count; loop1++) { if (MyCookieCollection.GetKey(loop1) == "LastVisit") { MyCookieCollection[loop1].Value = DateTime.Now.ToString(); MyCookieCollection.Set(MyCookieCollection[loop1]); } } // </Snippet1> }
internal void DeleteInternal(string name, string path, string domain, HttpCookieCollection requestCookies, HttpCookieCollection responseCookies) { foreach (HttpCookie current in this.GetCookieChunks(name, requestCookies)) { HttpCookie httpCookie = new HttpCookie(current.Name, null); httpCookie.Path = path; httpCookie.Expires = DateTime.UtcNow.AddDays(-1.0); if (!string.IsNullOrEmpty(domain)) { httpCookie.Domain = domain; } //if (DiagnosticUtility.ShouldTrace(TraceEventType.Information)) //{ // TraceUtility.TraceEvent(TraceEventType.Information, 786438, null, new ChunkedCookieHandlerTraceRecord(ChunkedCookieHandlerTraceRecord.Action.Deleting, current, path), null); //} responseCookies.Set(httpCookie); } }
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() }); }
/// <summary> /// Sets the cookie value. /// </summary> /// <param name="collection">The collection.</param> /// <param name="cookieName">Name of the cookie.</param> /// <param name="cookieValue">The cookie value.</param> /// <param name="expiry">The expiry.</param> private static void SetCookieValue(HttpCookieCollection collection, string cookieName, string cookieValue, DateTime expiry) { if (collection != null) { HttpCookie cookie = new HttpCookie(cookieName) { Value = cookieValue, Secure = true, HttpOnly = true }; // Set date only if persistence is allowed. if (!IsSessionOnlyCookieEnabled(collection)) { cookie.Expires = expiry; } // Set will ensure no duplicate keys are persisted. collection.Set(cookie); } }
public static AuthorizationContext GetAuthorizationContext(string cookieValue, string formValue) { HttpCookieCollection requestCookies = new HttpCookieCollection(); NameValueCollection formCollection = new NameValueCollection(); Mock <AuthorizationContext> mockAuthContext = new Mock <AuthorizationContext>(); mockAuthContext.Expect(c => c.HttpContext.Request.ApplicationPath).Returns("/SomeAppPath"); mockAuthContext.Expect(c => c.HttpContext.Request.Cookies).Returns(requestCookies); mockAuthContext.Expect(c => c.HttpContext.Request.Form).Returns(formCollection); if (!String.IsNullOrEmpty(cookieValue)) { requestCookies.Set(new HttpCookie(_antiForgeryTokenCookieName, cookieValue)); } if (!String.IsNullOrEmpty(formValue)) { formCollection.Set(AntiForgeryData.GetAntiForgeryTokenName(null), formValue); } return(mockAuthContext.Object); }
protected override WebResponse GetWebResponse(WebRequest request) { try { var r = base.GetWebResponse(request); if (r is HttpWebResponse) { ResponseUri = (r as HttpWebResponse).ResponseUri; } for (int i = 0; i < (r as HttpWebResponse).Cookies.Count; i++) { Cookie c = (r as HttpWebResponse).Cookies[i]; if (!c.Expired) { cookies.Remove(c.Name); HttpCookie c2 = new HttpCookie(c.Name, c.Value); c2.Expires = c.Expires; c2.Path = c.Path; c2.Domain = c.Domain; c2.HttpOnly = c.HttpOnly; cookies.Set(c2); this._cookieContainer.Add(c); } //this._cookieContainer.Add((r as HttpWebResponse).Cookies[i]); } // this._cookieContainer.Add((r as HttpWebResponse).Cookies); return(r); } catch { return(null); } }
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() }; }
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; }
public static void ClearLoginCookies(this HttpCookieCollection cookies) { cookies.Set(new HttpCookie(AuthoriseBaseAttribute.ACCESSTOKEN, "")); cookies.Set(new HttpCookie(AuthoriseBaseAttribute.REFRESHTOKEN, "")); cookies.Set(new HttpCookie(AuthoriseBaseAttribute.CURRENT_USERID, "")); }
/// <summary> /// Updates the value of an existing cookie in a cookie collection. /// </summary> /// <param name="cookie">The <see cref="T:System.Web.HttpCookie" /> object to update. </param> public void Set(HttpCookie cookie) { collection.Set(cookie); }