private CookieOptions CreateCookieOptions(bool? persistent, DateTimeOffset? expires = null) { var secure = _context.HttpContext.Request.IsHttps; var path = _context.GetBasePath().CleanUrlPath(); var options = new CookieOptions { HttpOnly = false, Secure = secure, Path = path }; // todo: load authN cookie and copy its values for persistent/expiration //if (persistent != false) //{ // if (persistent == true || _context.Options.AuthenticationOptions.CookieAuthenticationOptions.IsPersistent) // { // if (persistent == true) // { // expires = expires ?? DateTimeHelper.UtcNow.Add(this.identityServerOptions.AuthenticationOptions.CookieOptions.RememberMeDuration); // } // else // { // expires = expires ?? DateTimeHelper.UtcNow.Add(this.identityServerOptions.AuthenticationOptions.CookieOptions.ExpireTimeSpan); // } // options.Expires = expires.Value.UtcDateTime; // } //} return options; }
public AppendCookieContext(HttpContext context, CookieOptions options, string name, string value) { Context = context; CookieOptions = options; CookieName = name; CookieValue = value; }
protected virtual void KullanıcıÇereziniAyarla(Guid KullanıcıGuid) { if (_httpContextAccessor.HttpContext?.Response == null) { return; } _httpContextAccessor.HttpContext.Response.Cookies.Delete(KullanıcıÇerezAdı); var cookieExpires = 24 * 365; //TODO make configurable var cookieExpiresDate = DateTime.Now.AddHours(cookieExpires); if (KullanıcıGuid == Guid.Empty) { cookieExpiresDate = DateTime.Now.AddMonths(-1); } var options = new Microsoft.AspNetCore.Http.CookieOptions { HttpOnly = true, Expires = cookieExpiresDate }; _httpContextAccessor.HttpContext.Response.Cookies.Append(KullanıcıÇerezAdı, KullanıcıGuid.ToString(), options); }
/// <summary> /// Set store cookie /// </summary> /// <param name="customerGuid">Guid of the customer</param> protected virtual void SetStoreCookie(string storeId) { if (_httpContextAccessor.HttpContext == null || _httpContextAccessor.HttpContext.Response == null) { return; } var store = _storeService.GetStoreById(storeId); if (store == null) { return; } //delete current cookie value _httpContextAccessor.HttpContext.Response.Cookies.Delete(STORE_COOKIE_NAME); //get date of cookie expiration var cookieExpires = 24 * 365; //TODO make configurable var cookieExpiresDate = DateTime.Now.AddHours(cookieExpires); //set new cookie value var options = new Microsoft.AspNetCore.Http.CookieOptions { HttpOnly = true, Expires = cookieExpiresDate }; _httpContextAccessor.HttpContext.Response.Cookies.Append(STORE_COOKIE_NAME, storeId, options); }
public async Task <IViewComponentResult> InvokeAsync() { var options = new Microsoft.AspNetCore.Http.CookieOptions() { HttpOnly = true, SameSite = SameSiteMode.Strict, IsEssential = true, MaxAge = TimeSpan.FromDays(10), }; //ViewBag.IsLoggedIn = _signInManager.IsSignedIn(UserClaimsPrincipal); ViewBag.IsLoggedIn = User.Identity.IsAuthenticated; ViewBag.UserName = User.Identity.Name; if (!string.IsNullOrWhiteSpace(Request.Cookies["Test"])) { var obj = JsonConvert.DeserializeObject <TestClass>(Request.Cookies["Test"]); _logger.LogDebug("Cookie -> Key: {key} || String values: {value}", "Test", string.Join(", ", obj.Str)); } //foreach (var cookie in Request.Cookies) //{ // _logger.LogDebug("Cookie - Key: {key} | Value: {value}", cookie.Key, cookie.Value); //} //ViewBag.CartCount = Request.Cookies. var cookieVal = JsonConvert.SerializeObject(new TestClass()); _logger.LogDebug("Writing the cookie with value of" + string.Join(", ", cookieVal)); HttpContext.Response.Cookies.Append("Test", cookieVal, options); return(View("Navbar")); }
public void CookieDefault() { var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions(); cookieOptions.Secure = false; Response.Cookies.Append("auth", "secret", cookieOptions); // GOOD: Secure is set in callback }
/// <summary> /// Set game customer cookie /// </summary> /// <param name="customerGuid">Guid of the customer</param> protected virtual void SetCustomerCookie(Guid customerGuid) { if (_httpContextAccessor.HttpContext?.Response == null) { return; } //delete current cookie value _httpContextAccessor.HttpContext.Response.Cookies.Delete(CUSTOMER_COOKIE_NAME); //get date of cookie expiration var cookieExpires = 24 * 365; //TODO make configurable var cookieExpiresDate = DateTime.Now.AddHours(cookieExpires); //if passed guid is empty set cookie as expired if (customerGuid == Guid.Empty) { cookieExpiresDate = DateTime.Now.AddMonths(-1); } //set new cookie value var options = new Microsoft.AspNetCore.Http.CookieOptions { HttpOnly = true, Expires = cookieExpiresDate }; _httpContextAccessor.HttpContext.Response.Cookies.Append(CUSTOMER_COOKIE_NAME, customerGuid.ToString(), options); }
public static void SetKookies(this IResponseCookies cookies, string key, object value) { CookieOptions options = new Microsoft.AspNetCore.Http.CookieOptions(); options.Expires = DateTime.Now.AddSeconds(100); cookies.Append(key, JsonConvert.SerializeObject(value), options); }
/// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="minute"></param> public void SetCookie(string key, string value, int minute) { Microsoft.AspNetCore.Http.CookieOptions cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions(); cookieOptions.Path = "/"; cookieOptions.Expires = DateTimeOffset.Now.AddMinutes(minute); this._httpContextAccessor.HttpContext.Response.Cookies.Append(key, value, cookieOptions); }
public static IApplicationBuilder UseAuthController(this IApplicationBuilder app, IAuth _authService) { return(app.Use(async(context, next) => { if (context.Request.Cookies["access_token"] != null) { var secs = DateTime.Now.Subtract(DateTime.Parse(context.Request.Cookies["created"])).TotalSeconds; if (secs > 3400 && secs < 3600) { FirebaseAuth auth = new FirebaseAuth { Created = DateTime.Parse(context.Request.Cookies["created"]), ExpiresIn = int.Parse(context.Request.Cookies["expiresIn"]), FirebaseToken = context.Request.Cookies["access_token"], RefreshToken = context.Request.Cookies["refresh_token"], User = await _authService.GetUserAsync(context.Request.Cookies["access_token"]) }; var refresh = await _authService.RefreshLoginAsync(auth); context.Response.Cookies.Delete("access_token"); context.Response.Cookies.Delete("refresh_token"); context.Response.Cookies.Delete("expiresIn"); context.Response.Cookies.Delete("created"); context.Response.Cookies.Delete("email"); context.Response.Cookies.Delete("id"); Microsoft.AspNetCore.Http.CookieOptions cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions { Expires = DateTime.Now.AddSeconds(refresh.ExpiresIn + 300) }; context.Response.Cookies.Append("access_token", refresh.FirebaseToken, new Microsoft.AspNetCore.Http.CookieOptions { Expires = DateTime.Now.AddSeconds(refresh.ExpiresIn) }); context.Response.Cookies.Append("refresh_token", refresh.RefreshToken, cookieOptions); context.Response.Cookies.Append("expiresIn", refresh.ExpiresIn.ToString(), cookieOptions); context.Response.Cookies.Append("created", refresh.Created.ToString(), cookieOptions); context.Response.Cookies.Append("email", refresh.User.Email, cookieOptions); context.Response.Cookies.Append("id", refresh.User.LocalId, cookieOptions); } context.Request.Headers.Add("Authorization", "Bearer " + context.Request.Cookies["access_token"]); } else { if (!context.Request.Path.ToString().ToLower().Equals("/auth/login") && !context.Request.Path.ToString().ToLower().Equals("/authorization/authenticate")) { context.Response.Redirect("/auth/login"); return; } } await next(); })); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="options"></param> /// <param name="properties"></param> /// <param name="cookieOptions"></param> public CookieSigningOutContext( HttpContext context, CookieAuthenticationOptions options, AuthenticationProperties properties, CookieOptions cookieOptions) : base(context, options) { CookieOptions = cookieOptions; Properties = properties; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions() { Path = "/", HttpOnly = false, IsEssential = true, //<- there Expires = DateTime.Now.AddMonths(1), }; RegisterLayers(services); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddHttpContextAccessor(); services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromDays(10); }); services.AddAuthentication().AddCookie(o => { o.ExpireTimeSpan = TimeSpan.FromDays(10); }); //Localization services.AddSingleton <LocService>(); services.AddLocalization(options => options.ResourcesPath = "Resources"); services.AddMvc() .AddMvcLocalization(opt => { opt.ResourcesPath = "Resources"; }) .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) .AddDataAnnotationsLocalization() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.Configure <RequestLocalizationOptions>(opt => { var supportlang = new List <CultureInfo>() { new CultureInfo("en"), new CultureInfo("ar"), new CultureInfo("it") }; opt.DefaultRequestCulture = new RequestCulture("en"); opt.SupportedCultures = supportlang; opt.SupportedUICultures = supportlang; }); }
public override void AddSessionCookie(string cookieName, string cookieValue, bool?secureOnly = null) { var options = new Microsoft.AspNetCore.Http.CookieOptions { Path = RootPath, }; if (secureOnly != null) { options.Secure = secureOnly.Value; } response.Cookies.Append(cookieName, cookieValue, options); }
/// <summary> /// Creates a new instance of the context object. /// </summary> /// <param name="context">The HTTP request context</param> /// <param name="options">The middleware options</param> /// <param name="authenticationScheme">Initializes AuthenticationScheme property</param> /// <param name="principal">Initializes Principal property</param> /// <param name="properties">Initializes Extra property</param> /// <param name="cookieOptions">Initializes options for the authentication cookie.</param> public CookieSigningInContext( HttpContext context, CookieAuthenticationOptions options, string authenticationScheme, ClaimsPrincipal principal, AuthenticationProperties properties, CookieOptions cookieOptions) : base(context, options) { AuthenticationScheme = authenticationScheme; Principal = principal; Properties = properties; CookieOptions = cookieOptions; }
public override void AddPermanentCookie(string cookieName, string cookieValue, bool?secureOnly = null) { var options = new Microsoft.AspNetCore.Http.CookieOptions { Path = RootPath, Expires = DateTime.UtcNow.AddYears(20) }; if (secureOnly != null) { options.Secure = secureOnly.Value; } response.Cookies.Append(cookieName, cookieValue, options); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions() { Path = "/", HttpOnly = false, IsEssential = true, //<- there Expires = DateTime.Now.AddMonths(1), }; }); services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromSeconds(10); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); services.AddDbContext <IntellectDbContext>(x => { x.UseSqlServer(Configuration["Database:IntellectDb"]); }); services.AddIdentity <ExamUser, IdentityRole>(options => { // options.SignIn.RequireConfirmedEmail = true; #region Password configuration options.Password.RequireDigit = true; options.Password.RequireLowercase = true; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = true; #endregion options.Lockout.MaxFailedAccessAttempts = 9; // options.User.AllowedUserNameCharacters = "qwertyuiopasdfghjklzxcvbnm"; options.User.RequireUniqueEmail = true; }) .AddEntityFrameworkStores <IntellectDbContext>() .AddDefaultTokenProviders(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
private void SaveChanges() { var cookieList = _lineCollection.Select(s => new CookieCartLine { GameId = s.Game.GameId, Quantity = s.Quantity }).ToList(); var jsonString = JsonConvert.SerializeObject(cookieList); var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions() { //Path = "/", HttpOnly = false, IsEssential = true, //<- there Expires = DateTime.Now.AddMonths(1), }; _httpContext.Response.Cookies.Append(CartCookieName, jsonString, cookieOptions); }
public IActionResult Index() { // Cookie var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions() { Path = "/", HttpOnly = false, IsEssential = true, //<- there Expires = DateTime.Now.AddMonths(1), }; Response.Cookies.Append("Name", "Stephan", cookieOptions); // Session HttpContext.Session.SetString("PlayerName", "Player 2"); return(View()); }
public async Task <ActionResult> Login(LoginAndRegisterViewModel model) { using (HttpClient client = new HttpClient()) { var uri = new Uri("https://localhost:44310/api/auth/login"); var login = new LoginViewModel() { Username = model.Login.Username, Password = model.Login.Password }; var jsonLogin = JsonConvert.SerializeObject(login); var result = await client.PostAsync(uri, new StringContent(jsonLogin, Encoding.UTF8, "application/json")); var res = JsonConvert.SerializeObject(result.Content.ReadAsStringAsync().Result); res = res.Replace("\\\"\"", ""); res = res.Replace("\"\\\"", ""); var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions() { Path = "/", HttpOnly = false, IsEssential = true, Expires = DateTime.UtcNow.AddDays(10) }; var jwtToken = new JwtSecurityToken(res); List <Claim> claims = jwtToken.Payload.Claims.ToList(); string claimType = claims[2].Type.ToString(); //kullanici claim`i cookie`e eklenir. Response.Cookies.Append("claimType", claimType, cookieOptions); //token cookie`e eklenir. Response.Cookies.Append("authenticateUser", res, cookieOptions); //eger rememberMe secmis ise, userName cookie`e eklenir. her giris yapmak istediginde cookie`de kayitli userName var ise input`a yazar. if (model.Login.RememberMe) { Response.Cookies.Append("userName", model.Login.Username, cookieOptions); } } return(RedirectToAction("Index", "Product")); }
public void SaveCookieToken(HttpContext httpContext, string token) { Debug.Assert(httpContext != null); Debug.Assert(token != null); var options = new CookieOptions() { HttpOnly = true }; // Note: don't use "newCookie.Secure = _options.RequireSSL;" since the default // value of newCookie.Secure is poulated out of band. if (_options.RequireSsl) { options.Secure = true; } //httpContext.Response.Cookies.Append(_options.CookieName, token, options); var tenant = httpContext.GetTenant<SiteContext>(); if (tenant.SiteFolderName.Length > 0) options.Path = new PathString("/" + tenant.SiteFolderName); httpContext.Response.Cookies.Append(_options.CookieName + tenant.SiteFolderName, token, options); }
public ActionResult FinalizeEvent([FromBody]EventViewModel currentModel) { if (ModelState.IsValid) { string eventCookie = HttpContext.Request.Cookies["NewEvent"]; if (eventCookie != null) { EventViewModel memoryModel = eventCookie.FromJson<EventViewModel>(); if (memoryModel.ClubId != 0) { currentModel.ClubId = memoryModel.ClubId; currentModel.UserID = _userManager.GetUserId(User); } else currentModel.UserID = _userManager.GetUserId(User); } currentModel.DateCreated = DateTime.Now.ToString(); SingleModelResponse<Event> eventResponse = _context.SaveEvent(currentModel); if (eventResponse.DidError == true || eventResponse == null) { if (eventResponse == null) return View("Error"); Error er = new Error(eventResponse.ErrorMessage); return View("Error"); } var CookieOption = new CookieOptions(); CookieOption.Expires = DateTime.Now.AddDays(-1); CookieOption.HttpOnly = true; //set cookie HttpContext.Response.Cookies.Append("NewEvent", currentModel.ToJson(), CookieOption); CookieOption = new CookieOptions(); CookieOption.Expires = DateTime.Now.AddMinutes(1); CookieOption.HttpOnly = true; string source = "Add"; //set cookie HttpContext.Response.Cookies.Append("SourcePageEvent", source, CookieOption); return RedirectToAction("Events"); } else { return BadRequest(); } }
/// <summary> /// Deletes the cookie with the given key by setting an expired state. If a matching chunked cookie exists on /// the request, delete each chunk. /// </summary> /// <param name="context"></param> /// <param name="key"></param> /// <param name="options"></param> public void DeleteCookie(HttpContext context, string key, CookieOptions options) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var keys = new List<string>(); keys.Add(key + "="); var requestCookie = context.Request.Cookies[key]; var chunks = ParseChunksCount(requestCookie); if (chunks > 0) { for (int i = 1; i <= chunks + 1; i++) { var subkey = key + ChunkKeySuffix + i.ToString(CultureInfo.InvariantCulture); keys.Add(subkey + "="); } } var domainHasValue = !string.IsNullOrEmpty(options.Domain); var pathHasValue = !string.IsNullOrEmpty(options.Path); Func<string, bool> rejectPredicate; Func<string, bool> predicate = value => keys.Any(k => value.StartsWith(k, StringComparison.OrdinalIgnoreCase)); if (domainHasValue) { rejectPredicate = value => predicate(value) && value.IndexOf("domain=" + options.Domain, StringComparison.OrdinalIgnoreCase) != -1; } else if (pathHasValue) { rejectPredicate = value => predicate(value) && value.IndexOf("path=" + options.Path, StringComparison.OrdinalIgnoreCase) != -1; } else { rejectPredicate = value => predicate(value); } var responseHeaders = context.Response.Headers; var existingValues = responseHeaders[Constants.Headers.SetCookie]; if (!StringValues.IsNullOrEmpty(existingValues)) { responseHeaders[Constants.Headers.SetCookie] = existingValues.Where(value => !rejectPredicate(value)).ToArray(); } AppendResponseCookie( context, key, string.Empty, new CookieOptions() { Path = options.Path, Domain = options.Domain, Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), }); for (int i = 1; i <= chunks; i++) { AppendResponseCookie( context, key + "C" + i.ToString(CultureInfo.InvariantCulture), string.Empty, new CookieOptions() { Path = options.Path, Domain = options.Domain, Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), }); } }
/// <summary></summary> public void Set(string p_key, string p_sub_key, string p_value, string p_domain, int?p_remain_days, Encrypt?p_encrypt, string p_encrypt_key) { // string value = ""; //HttpContext context = System.Web.HttpContext.Current; Encrypt encrypt = Encrypt.BASE64; int remain_days = 0; // if (p_encrypt.HasValue) { encrypt = p_encrypt.Value; } //p_key = context.Server.UrlEncode(p_key); p_key = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(p_key)); if (p_sub_key != null) { string cookieValue = Get(p_key, p_encrypt, p_encrypt_key); if (cookieValue == null || cookieValue.Trim().Length < 1) { cookieValue = ""; } char[] delim_cookieValues = { '&' }; string[] cookieValues = cookieValue.Split(delim_cookieValues); bool existChk = false; for (int cnti = 0; cnti < cookieValues.Length; cnti++) { if (cookieValues[cnti].IndexOf(p_sub_key + "=") == 0) { cookieValues[cnti] = p_sub_key + "=" + p_value; existChk = true; } if (cnti > 0) { value += "&"; } value += cookieValues[cnti]; } if (!existChk) { if (value.Trim().Length > 0) { value += "&"; } value += p_sub_key + "=" + p_value; } } else { value = p_value; } // switch (encrypt) { case Encrypt.PLAIN: break; case Encrypt.BASE64: // BASE64 인코딩된 자료에 대한 반환 처리 value = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(UrlEncoder.Default.Encode(value))); break; case Encrypt.AES256: // AES256 인코딩된 자료에 대한 반환 처리 //net.imcore.AES256Cipher aes = new net.imcore.AES256Cipher(); value = new AZEncrypt.AES256().Enc(value, p_encrypt_key); //aes.Encode(value, p_encrypt_key); //aes = null; break; } // /*HttpCookie cookies = new HttpCookie(p_key); * cookies.Value = value;*/ // /*if (p_domain != null) { * cookies.Domain = p_domain; * }*/ // if (p_remain_days.HasValue) { remain_days = p_remain_days.Value; } //cookies.Expires = DateTime.Today.AddDays(remain_days); //context.Response.Cookies.Set(cookies); // Microsoft.AspNetCore.Http.CookieOptions options = new Microsoft.AspNetCore.Http.CookieOptions(); options.Expires = DateTime.Today.AddDays(remain_days); if (p_domain != null) { options.Domain = p_domain; } context.Response.Cookies.Delete(p_key); context.Response.Cookies.Append(p_key, value, options); }
public void Delete(string key, CookieOptions options) { throw new NotImplementedException(); }
public IActionResult Edit([FromBody]Club ClubForm) { if (ModelState.IsValid) { Club club = new Club { ClubId = ClubForm.ClubId, Description = ClubForm.Description, Name = ClubForm.Name, Location = ClubForm.Location, DateCreated = ClubForm.DateCreated, UserId = _userManager.GetUserId(User) }; SingleModelResponse<Club> clubResponse = _context.UpdateClub(club); if (clubResponse.DidError == true || clubResponse == null) { if (clubResponse == null) return View("Error"); Error er = new Error(clubResponse.ErrorMessage); return View("Error", er); } var CookieOption = new CookieOptions(); CookieOption.Expires = DateTime.Now.AddMinutes(1); CookieOption.HttpOnly = true; string source = "Edit"; //set cookie HttpContext.Response.Cookies.Append("SourcePageClub", source, CookieOption); return RedirectToAction("ClubDetails", new { id = clubResponse.Model.ClubId }); } else { return BadRequest(); } }
public IActionResult DeRegisterMember(int MemberId) { if (ModelState.IsValid) { SingleModelResponse<ClubMember> clubResponse = _memberContext.DeRegisterMember(MemberId); if (clubResponse.DidError == true || clubResponse == null) { if (clubResponse == null) return View("Error"); Error er = new Error(clubResponse.ErrorMessage); return View("Error", er); } var CookieOption = new CookieOptions(); CookieOption.Expires = DateTime.Now.AddMinutes(1); CookieOption.HttpOnly = true; string source = "Delete"; //set cookie HttpContext.Response.Cookies.Append("SourcePageClubMember", source, CookieOption); return RedirectToAction("ClubDetails",clubResponse.Model.ClubId); } else { return BadRequest(); } }
//[ValidateAntiForgeryToken] public async Task<IActionResult> AddRoute([FromBody]RouteViewModel route) { if (ModelState.IsValid) { string userID = _userManager.GetUserId(User); SingleModelResponse<Route> routeResponse = await Task.Run(()=> _context.SaveRoute(route,userID)); if (routeResponse.DidError == true || routeResponse == null) { if (routeResponse == null) return View("Error"); Error er = new Error(routeResponse.ErrorMessage); return View("Error",er); } var CookieOption = new CookieOptions(); CookieOption.Expires = DateTime.Now.AddMinutes(1); CookieOption.HttpOnly = true; string source = "Add"; //set cookie HttpContext.Response.Cookies.Append("SourcePageMap", source, CookieOption); string url = Url.Action("SavedRoutes", "Map"); return Json(new { Url = url }); } else { var errors = ModelState.Values.SelectMany(v => v.Errors); Debug.WriteLine("Errors found: " + errors + "\nEnd Errors found"); return BadRequest(ModelState); } }
private void ApplyPolicy(CookieOptions options) { switch (Policy.Secure) { case SecurePolicy.Always: options.Secure = true; break; case SecurePolicy.SameAsRequest: options.Secure = Context.Request.IsHttps; break; case SecurePolicy.None: break; default: throw new InvalidOperationException(); } switch (Policy.HttpOnly) { case HttpOnlyPolicy.Always: options.HttpOnly = true; break; case HttpOnlyPolicy.None: break; default: throw new InvalidOperationException(); } }
public void Append(string key, string value, CookieOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } ApplyPolicy(options); if (Policy.OnAppendCookie != null) { var context = new AppendCookieContext(Context, options, key, value); Policy.OnAppendCookie(context); key = context.CookieName; value = context.CookieValue; } Cookies.Append(key, value, options); }
public void Delete(string key, CookieOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } ApplyPolicy(options); if (Policy.OnDeleteCookie != null) { var context = new DeleteCookieContext(Context, options, key); Policy.OnDeleteCookie(context); key = context.CookieName; } Cookies.Delete(key, options); }
public DeleteCookieContext(HttpContext context, CookieOptions options, string name) { Context = context; CookieOptions = options; CookieName = name; }
/// <summary> /// Appends a new response cookie to the Set-Cookie header. If the cookie is larger than the given size limit /// then it will be broken down into multiple cookies as follows: /// Set-Cookie: CookieName=chunks-3; path=/ /// Set-Cookie: CookieNameC1=Segment1; path=/ /// Set-Cookie: CookieNameC2=Segment2; path=/ /// Set-Cookie: CookieNameC3=Segment3; path=/ /// </summary> /// <param name="context"></param> /// <param name="key"></param> /// <param name="value"></param> /// <param name="options"></param> public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var template = new SetCookieHeaderValue(key) { Domain = options.Domain, Expires = options.Expires, HttpOnly = options.HttpOnly, Path = options.Path, Secure = options.Secure, }; var templateLength = template.ToString().Length; value = value ?? string.Empty; // Normal cookie var responseCookies = context.Response.Cookies; if (!ChunkSize.HasValue || ChunkSize.Value > templateLength + value.Length) { responseCookies.Append(key, value, options); } else if (ChunkSize.Value < templateLength + 10) { // 10 is the minimum data we want to put in an individual cookie, including the cookie chunk identifier "CXX". // No room for data, we can't chunk the options and name throw new InvalidOperationException(Resources.Exception_CookieLimitTooSmall); } else { // Break the cookie down into multiple cookies. // Key = CookieName, value = "Segment1Segment2Segment2" // Set-Cookie: CookieName=chunks-3; path=/ // Set-Cookie: CookieNameC1="Segment1"; path=/ // Set-Cookie: CookieNameC2="Segment2"; path=/ // Set-Cookie: CookieNameC3="Segment3"; path=/ var dataSizePerCookie = ChunkSize.Value - templateLength - 3; // Budget 3 chars for the chunkid. var cookieChunkCount = (int)Math.Ceiling(value.Length * 1.0 / dataSizePerCookie); responseCookies.Append(key, ChunkCountPrefix + cookieChunkCount.ToString(CultureInfo.InvariantCulture), options); var offset = 0; for (var chunkId = 1; chunkId <= cookieChunkCount; chunkId++) { var remainingLength = value.Length - offset; var length = Math.Min(dataSizePerCookie, remainingLength); var segment = value.Substring(offset, length); offset += length; responseCookies.Append(key + ChunkKeySuffix + chunkId.ToString(CultureInfo.InvariantCulture), segment, options); } } }
//[ValidateAntiForgeryToken] public IActionResult Edit([FromBody]RouteViewModel route) { if (ModelState.IsValid) { route.UserID = _userManager.GetUserId(User); SingleModelResponse<Route> routeResponse = _context.UpdateRoute(route); if (routeResponse.DidError == true || routeResponse == null) { if (routeResponse == null) return View("Error"); Error er = new Error(routeResponse.ErrorMessage); return View("Error"); } var CookieOption = new CookieOptions(); CookieOption.Expires = DateTime.Now.AddMinutes(1); CookieOption.HttpOnly = true; string source = "Edit"; //set cookie HttpContext.Response.Cookies.Append("SourcePageMap", source, CookieOption); return RedirectToAction("SavedRoutes"); } else { return BadRequest(ModelState); } }
public static string Login(HttpContext context, Guid userId, DateTime? modifiedOn, bool rememberMe ) { var identity = CreateIdentity(userId); if (identity == null) throw new Exception("Try to login with invalid user."); if (modifiedOn != identity.User.ModifiedOn) modifiedOn = identity.User.ModifiedOn; ErpUser user = new SecurityManager().GetUser(userId); string token = AuthToken.Create(user, rememberMe).Encrypt(); if (rememberMe) { CookieOptions options = new CookieOptions(); options.Expires = DateTime.Today.AddDays(AUTH_REMEMBER_IDENTITY_DAYS); context.Response.Cookies.Append(AUTH_TOKEN_KEY, token, options); } else context.Response.Cookies.Append(AUTH_TOKEN_KEY, token); context.User = new ErpPrincipal(identity); new SecurityManager().UpdateUserLastLoginTime(userId); return token; }
/// <summary></summary> public void Set <T>(string p_key, T p_model, string p_domain, int?p_remain_days, Encrypt?p_encrypt, string p_encrypt_key) { string key, value = ""; Encrypt encrypt = Encrypt.BASE64; int remain_days = 0; // //HttpContext context = System.Web.HttpContext.Current; // 쿠키 최상위 이름값이 없으면 모델의 이름으로 지정 key = p_key != null ? p_key : p_model.GetType().Name; key = UrlEncoder.Default.Encode(key);//context.Server.UrlEncode(key); // T -> AZData 형식으로 변환 AZData data = AZString.JSON.Init(AZString.JSON.Convert <T>(p_model)).ToAZData(); for (int cnti = 0; cnti < data.Size(); cnti++) { value += (cnti > 0 ? "&" : "") + data.GetKey(cnti) + "=" + UrlEncoder.Default.Encode(data.GetString(cnti));//context.Server.UrlEncode(data.GetString(cnti)); } // if (p_encrypt.HasValue) { encrypt = p_encrypt.Value; } // switch (encrypt) { case Encrypt.PLAIN: break; case Encrypt.BASE64: // BASE64 인코딩된 자료에 대한 반환 처리 value = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(UrlEncoder.Default.Encode(value))); break; case Encrypt.AES256: // AES256 인코딩된 자료에 대한 반환 처리 //net.imcore.AES256Cipher aes = new net.imcore.AES256Cipher(); value = new AZEncrypt.AES256().Enc(value, p_encrypt_key); //aes.Encode(value, p_encrypt_key); //aes = null; break; } // //HttpCookie cookies = new HttpCookie(key); //cookies.Value = value; // /*if (p_domain != null) { * cookies.Domain = p_domain; * }*/ // if (p_remain_days.HasValue) { remain_days = p_remain_days.Value; } Microsoft.AspNetCore.Http.CookieOptions options = new Microsoft.AspNetCore.Http.CookieOptions(); options.Expires = DateTime.Today.AddDays(remain_days); if (p_domain != null) { options.Domain = p_domain; } context.Response.Cookies.Delete(p_key); context.Response.Cookies.Append(p_key, value, options); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions() { Path = "/", HttpOnly = false, IsEssential = true, //<- there Expires = DateTime.Now.AddMonths(1), }; }); //Add Localization services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; }); services.AddDbContext <OfferDbContext>(x => { x.UseSqlServer(Configuration["Database:OfferDb"]); }); // for FileUpload services.AddSingleton <IFileProvider>( new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "wwwroot") )); services.AddIdentity <AppUser, IdentityRole>(options => { // options.SignIn.RequireConfirmedEmail = true; #region Password configuration options.Password.RequireDigit = true; options.Password.RequireLowercase = true; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = true; #endregion options.Lockout.MaxFailedAccessAttempts = 9; // options.User.AllowedUserNameCharacters = "qwertyuiopasdfghjklzxcvbnm"; options.User.RequireUniqueEmail = true; }) .AddEntityFrameworkStores <OfferDbContext>() .AddDefaultTokenProviders(); services.AddMvc(). AddViewLocalization(opts => { opts.ResourcesPath = "Resources"; }).AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix, opts => { opts.ResourcesPath = "Resources"; }). AddDataAnnotationsLocalization(). SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddAntiforgery(a => a.HeaderName = "XSRF-TOKEN"); services.Configure <RequestLocalizationOptions>(opts => { var supportedCultures = new List <CultureInfo> { new CultureInfo("az-Latn-AZ"), new CultureInfo("en-GB") }; opts.DefaultRequestCulture = new RequestCulture("az-Latn-AZ"); opts.SupportedCultures = supportedCultures; opts.SupportedUICultures = supportedCultures; // services.AddSingleton(opts); }); }
public void Append(string key, string value, CookieOptions options) { this.Key = key; this.Value = value; this.Options = options; this.Count++; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddLocalization(options => options.ResourcesPath = "Resources"); services.Configure <RequestLocalizationOptions>(options => { var cultures = new List <CultureInfo> { new CultureInfo("en"), new CultureInfo("bg"), }; options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("bg"); options.SupportedCultures = cultures; options.SupportedUICultures = cultures; options.RequestCultureProviders = new List <IRequestCultureProvider> { new CookieRequestCultureProvider(), new QueryStringRequestCultureProvider(), }; }); services.AddMvc() .AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix) .AddDataAnnotationsLocalization(); services.AddDbContext <ApplicationDbContext>( options => options.UseSqlServer(this.configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity <ApplicationUser>(IdentityOptionsProvider.GetIdentityOptions) .AddRoles <ApplicationRole>().AddEntityFrameworkStores <ApplicationDbContext>(); // Cloudinary setup Account cloudinaryCredentials = new Account( this.configuration["Cloudinary:CloudName"], this.configuration["Cloudinary:ApiKey"], this.configuration["Cloudinary:ApiSecret"]); Cloudinary cloudinaryUtility = new Cloudinary(cloudinaryCredentials); services.AddSingleton(cloudinaryUtility); services.AddResponseCaching(); // External Logins services.AddAuthentication() .AddGoogle(googleOptions => { IConfigurationSection googleAuthNSection = this.configuration.GetSection("Authentication:Google"); googleOptions.ClientId = googleAuthNSection["ClientId"]; googleOptions.ClientSecret = googleAuthNSection["ClientSecret"]; }) .AddFacebook(facebookOptions => { facebookOptions.AppId = this.configuration["Authentication:Facebook:AppId"]; facebookOptions.AppSecret = this.configuration["Authentication:Facebook:AppSecret"]; }); services.Configure <CookiePolicyOptions>( options => { options.CheckConsentNeeded = context => true; }); var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions() { Path = "/", HttpOnly = false, IsEssential = true, Expires = DateTime.Now.AddMonths(1), }; services.AddControllersWithViews(configure => { configure.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); }); services.AddAntiforgery(options => { options.HeaderName = "X-CSRF-TOKEN"; }); services.AddRazorPages().AddRazorRuntimeCompilation(); services.AddSingleton(this.configuration); // Data repositories services.AddScoped(typeof(IDeletableEntityRepository <>), typeof(EfDeletableEntityRepository <>)); services.AddScoped(typeof(IRepository <>), typeof(EfRepository <>)); services.AddScoped <IDbQueryRunner, DbQueryRunner>(); services.AddResponseCompression(options => { options.EnableForHttps = true; }); // Application services services.AddTransient <IEmailSender>(x => new SendGridEmailSender(this.configuration["SendGrid:ApiKey"])); services.AddTransient <IArticleService, ArticleService>(); services.AddTransient <IVideoService, VideoService>(); services.AddTransient <ICloudinaryService, CloudinaryService>(); services.AddTransient <IUserService, UserService>(); services.AddTransient <IAppointmentService, AppointmentService>(); services.AddTransient <IArticleCommentService, ArticleCommentService>(); services.AddTransient <IVideoCommentService, VideoCommentService>(); services.AddTransient <ISearchService, SearchService>(); }
public void Append(string key, string value, CookieOptions options) { throw new NotImplementedException(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Home/Index"; options.LogoutPath = "/Home/LogOut"; }); services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. //options.CheckConsentNeeded = context => true; //options.MinimumSameSitePolicy = SameSiteMode.None; var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions() { Path = "/", HttpOnly = false, IsEssential = true, Expires = DateTime.Now.AddMonths(1), }; }); services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(60); options.Cookie.Name = ".GoCWebTemplate.Session"; options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped <IHRCaseRepository, HRCaseRepository>(); services.AddScoped <ICaseTypeRepository, CaseTypeRepository>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IQuestionRepository, QuestionRepository>(); services.AddScoped <IAnnotationRepository, AnnotationRepository>(); #region snippet1 services.AddLocalization(options => options.ResourcesPath = "Resources"); services.AddMvc() .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) .AddDataAnnotationsLocalization(); services.Configure <RequestLocalizationOptions>(options => { var supportedCultures = new List <CultureInfo> { new CultureInfo("en-CA"), new CultureInfo("fr") }; options.DefaultRequestCulture = new RequestCulture("en-CA"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); #endregion services.AddControllersWithViews(); services.AddAutoMapper(typeof(Startup)); services.Configure <Dynamics>(Configuration.GetSection("Dynamics")); services.Configure <HrApi>(Configuration.GetSection("HrApi")); services.AddModelAccessor(); services.ConfigureGoCTemplateRequestLocalization(); // >= v2.1.1 }
public IActionResult AddClub([FromForm]Club ClubForm) { if (ModelState.IsValid) { Club club = new Club { Name = ClubForm.Name, Description = ClubForm.Description, DateCreated = DateTime.Now.ToString(), Location = ClubForm.Location, UserId = _userManager.GetUserId(User), Deleted = false }; var CookieOption = new CookieOptions(); CookieOption.Expires = DateTime.Now.AddMinutes(10); CookieOption.HttpOnly = true; //set cookie HttpContext.Response.Cookies.Append("NewClub", club.ToJson(), CookieOption); return RedirectToAction("FinalizeClub"); } else { return View(ClubForm); } }
public IActionResult Delete([FromBody]int id) { if (ModelState.IsValid) { SingleModelResponse<Route> routeResponse = _context.DeleteRoute(id); if (routeResponse.DidError == true || routeResponse == null) { if (routeResponse == null) return View("Error"); Error er = new Error(routeResponse.ErrorMessage); return View("Error"); } var CookieOption = new CookieOptions(); CookieOption.Expires = DateTime.Now.AddMinutes(1); CookieOption.HttpOnly = true; string source = "Delete"; //set cookie HttpContext.Response.Cookies.Append("SourcePageMap", source, CookieOption); return RedirectToAction("SavedRoutes"); } else { var errors = ModelState.Values.SelectMany(v => v.Errors); Debug.WriteLine("Errors found: " + errors + "\nEnd Errors found"); return BadRequest(ModelState); } }
public async Task<IActionResult> CreateClub() { if (ModelState.IsValid) { Club saveClub = new Club(); string clubCookie = HttpContext.Request.Cookies["NewClub"]; if (clubCookie != null) { saveClub = clubCookie.FromJson<Club>(); } else return RedirectToAction("AddClub"); SingleModelResponse<Club> clubResponse = await Task.Run(() => _context.SaveClub(saveClub)); if (clubResponse.DidError == true || clubResponse == null) { if (clubResponse == null) return View("Error"); Error er = new Error(clubResponse.ErrorMessage); return View("Error"); } var CookieOption = new CookieOptions(); CookieOption.Expires = DateTime.Now.AddDays(-1); CookieOption.HttpOnly = true; //set cookie HttpContext.Response.Cookies.Append("NewEvent", saveClub.ToJson(), CookieOption); var CookieOption2 = new CookieOptions(); CookieOption.Expires = DateTime.Now.AddMinutes(1); CookieOption.HttpOnly = true; string source = "Add"; //set cookie HttpContext.Response.Cookies.Append("SourcePageClub", source, CookieOption); return RedirectToAction("Clubs"); } else { return BadRequest(ModelState); } }
public void AddPermanentCookie(string cookieName, string cookieValue, bool? secureOnly = null) { var options = new CookieOptions { Path = RootPath, Expires = DateTime.UtcNow.AddYears(20) }; if (secureOnly != null) { options.Secure = secureOnly.Value; } response.Cookies.Append(cookieName, cookieValue, options); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (!env.IsDevelopment()) { app.UseHealthChecksUI(); } app.UseHealthChecks("/hc/self", new HealthCheckOptions { Predicate = r => r.Name.Contains("self", StringComparison.InvariantCultureIgnoreCase) }); app.UseHealthChecks("/hc/ready", new HealthCheckOptions { // Predicate = r => r.Tags.Contains("services") }); app.UseHealthChecks("/hc/uiresponse", new HealthCheckOptions { ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); app.UseHealthChecks( "/hc", new HealthCheckOptions { ResponseWriter = (httpContext, result) => { httpContext.Response.ContentType = MediaTypeNames.Application.Json; var json = new JObject( new JProperty("status", result.Status.ToString()), new JProperty("atlasVersion", AppInfoUtils.InformationalVersion), new JProperty("atlasServiceName", AppInfoUtils.AtlasServiceName), new JProperty("checkedAt", DateTime.UtcNow)); return(httpContext.Response.WriteAsync(json.ToString(Formatting.Indented))); } }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSecurityHeaders(); app.UseAuthentication(); var config = Configuration.GetSection("AtlasApplication").Get <Models.ApplicationDetail>(); var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions() { Path = "/", HttpOnly = false, IsEssential = true }; app.Use(async(context, next) => { await next(); var path = context.Request.Path.Value; if (context.Response.StatusCode == 404 && (!Path.HasExtension(path) || (Path.HasExtension(path) && Regex.IsMatch(Path.GetExtension(path), @"[\d|\D]\d\d"))) && !path.StartsWith("/api/", StringComparison.Ordinal)) { context.Request.Path = "/"; await next(); } }); app.UseMvcWithDefaultRoute(); app.UseDefaultFiles(); app.UseStaticFiles(new StaticFileOptions() { OnPrepareResponse = (ctx) => { if (ctx.Context.Request.Path == "/index.html") { ctx.Context.Response.Cookies.Delete("EnvSuffix"); ctx.Context.Response.Cookies.Append("EnvSuffix", config.WebAppRoot, cookieOptions); } } }); }
public void AddSessionCookie(string cookieName, string cookieValue, bool? secureOnly = null) { var options = new CookieOptions { Path = RootPath, }; if (secureOnly != null) { options.Secure = secureOnly.Value; } response.Cookies.Append(cookieName, cookieValue, options); }
/// <summary> /// Appends a new response cookie to the Set-Cookie header. If the cookie is larger than the given size limit /// then it will be broken down into multiple cookies as follows: /// Set-Cookie: CookieName=chunks:3; path=/ /// Set-Cookie: CookieNameC1=Segment1; path=/ /// Set-Cookie: CookieNameC2=Segment2; path=/ /// Set-Cookie: CookieNameC3=Segment3; path=/ /// </summary> /// <param name="context"></param> /// <param name="key"></param> /// <param name="value"></param> /// <param name="options"></param> public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var escapedKey = Encoder.Encode(key); var template = new SetCookieHeaderValue(escapedKey) { Domain = options.Domain, Expires = options.Expires, HttpOnly = options.HttpOnly, Path = options.Path, Secure = options.Secure, }; var templateLength = template.ToString().Length; value = value ?? string.Empty; var quoted = false; if (IsQuoted(value)) { quoted = true; value = RemoveQuotes(value); } var escapedValue = Encoder.Encode(value); // Normal cookie var responseHeaders = context.Response.Headers; if (!ChunkSize.HasValue || ChunkSize.Value > templateLength + escapedValue.Length + (quoted ? 2 : 0)) { template.Value = quoted ? Quote(escapedValue) : escapedValue; responseHeaders.Append(Constants.Headers.SetCookie, template.ToString()); } else if (ChunkSize.Value < templateLength + (quoted ? 2 : 0) + 10) { // 10 is the minimum data we want to put in an individual cookie, including the cookie chunk identifier "CXX". // No room for data, we can't chunk the options and name throw new InvalidOperationException(Resources.Exception_CookieLimitTooSmall); } else { // Break the cookie down into multiple cookies. // Key = CookieName, value = "Segment1Segment2Segment2" // Set-Cookie: CookieName=chunks:3; path=/ // Set-Cookie: CookieNameC1="Segment1"; path=/ // Set-Cookie: CookieNameC2="Segment2"; path=/ // Set-Cookie: CookieNameC3="Segment3"; path=/ var dataSizePerCookie = ChunkSize.Value - templateLength - (quoted ? 2 : 0) - 3; // Budget 3 chars for the chunkid. var cookieChunkCount = (int)Math.Ceiling(escapedValue.Length * 1.0 / dataSizePerCookie); template.Value = "chunks:" + cookieChunkCount.ToString(CultureInfo.InvariantCulture); responseHeaders.Append(Constants.Headers.SetCookie, template.ToString()); var chunks = new string[cookieChunkCount]; var offset = 0; for (var chunkId = 1; chunkId <= cookieChunkCount; chunkId++) { var remainingLength = escapedValue.Length - offset; var length = Math.Min(dataSizePerCookie, remainingLength); var segment = escapedValue.Substring(offset, length); offset += length; template.Name = escapedKey + "C" + chunkId.ToString(CultureInfo.InvariantCulture); template.Value = quoted ? Quote(segment) : segment; chunks[chunkId - 1] = template.ToString(); } responseHeaders.Append(Constants.Headers.SetCookie, chunks); } }
public IActionResult CreateEvent(EventViewModel model, int[] RouteId) { if (ModelState.IsValid) { if (model.EventRoutes == null) { model.EventRoutes = new List<EventRouteViewModel>(); } foreach (int id in RouteId) { SingleModelResponse<Route> routeResponse = _routeContext.GetRoute(id); if (routeResponse.DidError == true || routeResponse == null) { if (routeResponse == null) return View("Error"); Error er = new Error(routeResponse.ErrorMessage); return View("Error"); } model.EventRoutes.Add(routeResponse.Model.ToEventRouteViewModel()); } if (model.ClubId != 0) { SingleModelResponse<Club> clubResponse = _clubContext.GetClub(model.ClubId); if (clubResponse.DidError == true || clubResponse == null) { if (clubResponse == null) return View("Error"); Error er = new Error(clubResponse.ErrorMessage); return View("Error"); } model.ClubName = clubResponse.Model.Name; } //example of using cookie var CookieOption = new CookieOptions(); CookieOption.Expires = DateTime.Now.AddMinutes(5); CookieOption.HttpOnly = true; //set cookie HttpContext.Response.Cookies.Append("NewEvent", model.ToJson(), CookieOption); return RedirectToAction("FinalizeEvent"); } else { return View(model); } }
private static void GenerateCorrelationId(HttpContext context, OpenIdConnectOptions options, AuthenticationProperties properties) { if (properties == null) { throw new ArgumentNullException(nameof(properties)); } var bytes = new byte[32]; CryptoRandom.GetBytes(bytes); var correlationId = Base64UrlTextEncoder.Encode(bytes); var cookieOptions = new CookieOptions { HttpOnly = true, Secure = context.Request.IsHttps, Expires = DateTimeOffset.UtcNow + options.ProtocolValidator.NonceLifetime }; properties.Items[CorrelationProperty] = correlationId; var cookieName = CookieStatePrefix + OpenIdConnectDefaults.AuthenticationScheme + "." + correlationId; context.Response.Cookies.Append(cookieName, NonceProperty, cookieOptions); }
public ActionResult Delete([FromBody]int id) { if (ModelState.IsValid) { SingleModelResponse<Event> eventResponse = _context.DeleteEvent(id); if (eventResponse.DidError == true || eventResponse == null) { if (eventResponse == null) return View("Error"); Error er = new Error(eventResponse.ErrorMessage); return View("Error"); } var CookieOption = new CookieOptions(); CookieOption.Expires = DateTime.Now.AddMinutes(1); CookieOption.HttpOnly = true; string source = "Delete"; //set cookie HttpContext.Response.Cookies.Append("SourcePageEvent", source, CookieOption); return RedirectToAction("Events"); } else { return BadRequest(); } }
/// <inheritdoc /> public void Append(ReadOnlySpan <KeyValuePair <string, string> > keyValuePairs, CookieOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } // SameSite=None cookies must be marked as Secure. if (!options.Secure && options.SameSite == SameSiteMode.None) { if (_logger == null) { var services = _features.Get <IServiceProvidersFeature>()?.RequestServices; _logger = services?.GetService <ILogger <ResponseCookies> >(); } if (_logger != null) { foreach (var keyValuePair in keyValuePairs) { Log.SameSiteCookieNotSecure(_logger, keyValuePair.Key); } } } var setCookieHeaderValue = new SetCookieHeaderValue(string.Empty) { Domain = options.Domain, Path = options.Path, Expires = options.Expires, MaxAge = options.MaxAge, Secure = options.Secure, SameSite = (Net.Http.Headers.SameSiteMode)options.SameSite, HttpOnly = options.HttpOnly }; var cookierHeaderValue = setCookieHeaderValue.ToString()[1..];
public IActionResult Edit([FromBody]EventViewModel evnt) { if (ModelState.IsValid) { evnt.EventRoutes = new List<EventRouteViewModel>(); foreach (int id in evnt.RouteId) { SingleModelResponse<Route> routeResponse = _routeContext.GetRoute(id); if (routeResponse.DidError == true || routeResponse == null) { if (routeResponse == null) return View("Error"); Error er = new Error(routeResponse.ErrorMessage); return View("Error"); } evnt.EventRoutes.Add(routeResponse.Model.ToEventRouteViewModel()); } SingleModelResponse<Event> eventResponse = _context.UpdateEvent(evnt); if (eventResponse.DidError == true) { Error er = new Error(eventResponse.ErrorMessage); return View("Error"); } var CookieOption = new CookieOptions(); CookieOption.Expires = DateTime.Now.AddMinutes(1); CookieOption.HttpOnly = true; string source = "Edit"; //set cookie HttpContext.Response.Cookies.Append("SourcePageEvent", source, CookieOption); return RedirectToAction("EventDetails", new { id = evnt.EventId }); } else { return View("EditEvent", evnt); } }