void SetDefault()
 {
     SessionExpire = TimeSpan.FromDays(30);
     CookieName = "session";
     SessionKeyGenerator = () => Guid.NewGuid().ToString();
     SetCookieOptions = new CookieOptions();
 }
		public void Append(string key, string value, CookieOptions options) {
			HttpCookie cookie = new HttpCookie(key, value) {
				Path = options.Path
			};

			if (!String.IsNullOrEmpty(options.Domain)) cookie.Domain = options.Domain;
			if (options.Secure) cookie.Secure = true;
			if (options.HttpOnly) cookie.HttpOnly = true;
			if (options.Expires != null) cookie.Expires = options.Expires.Value;

			_cookies.Add(cookie); // internally this performs an append
		}
Ejemplo n.º 3
0
        /// <summary>
        /// Add a new cookie
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="options"></param>
        public void Append(string key, string value, CookieOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var setCookieHeaderValue = new SetCookieHeaderValue(
                    UrlEncoder.Default.Encode(key),
                    UrlEncoder.Default.Encode(value))
            {
                Domain = options.Domain,
                Path = options.Path,
                Expires = options.Expires,
                Secure = options.Secure,
                HttpOnly = options.HttpOnly,
            };

            Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], setCookieHeaderValue.ToString());
        }
Ejemplo n.º 4
0
        /// <inheritdoc />
        public void Append(string key, string value, CookieOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var setCookieHeaderValue = new SetCookieHeaderValue(
                Uri.EscapeDataString(key),
                Uri.EscapeDataString(value))
            {
                Domain = options.Domain,
                Path = options.Path,
                Expires = options.Expires,
                Secure = options.Secure,
                HttpOnly = options.HttpOnly,
            };

            string cookieValue;
            if (_builderPool == null)
            {
                cookieValue = setCookieHeaderValue.ToString();
            }
            else
            {
                var stringBuilder = _builderPool.Get();
                try
                {
                    setCookieHeaderValue.AppendToStringBuilder(stringBuilder);
                    cookieValue = stringBuilder.ToString();
                }
                finally
                {
                    _builderPool.Return(stringBuilder);
                }
            }

            Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], cookieValue);
        }
Ejemplo n.º 5
0
        /// <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(IOwinContext context, string key, string value, CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var webContext = context.Get <HttpContextBase>(typeof(HttpContextBase).FullName);

            if (webContext == null)
            {
                Fallback.AppendResponseCookie(context, key, value, options);
                return;
            }

            bool domainHasValue   = !string.IsNullOrEmpty(options.Domain);
            bool pathHasValue     = !string.IsNullOrEmpty(options.Path);
            bool expiresHasValue  = options.Expires.HasValue;
            bool sameSiteHasValue = options.SameSite.HasValue && SystemWebCookieManager.IsSameSiteAvailable;

            string escapedKey = Uri.EscapeDataString(key);
            string prefix     = escapedKey + "=";

            string suffix = string.Concat(
                !domainHasValue ? null : "; domain=",
                !domainHasValue ? null : options.Domain,
                !pathHasValue ? null : "; path=",
                !pathHasValue ? null : options.Path,
                !expiresHasValue ? null : "; expires=",
                !expiresHasValue ? null : options.Expires.Value.ToString("ddd, dd-MMM-yyyy HH:mm:ss \\G\\M\\T", CultureInfo.InvariantCulture),
                !options.Secure ? null : "; secure",
                !options.HttpOnly ? null : "; HttpOnly",
                !sameSiteHasValue ? null : "; SameSite=",
                !sameSiteHasValue ? null : GetStringRepresentationOfSameSite(options.SameSite.Value)
                );

            value = value ?? string.Empty;
            bool quoted = false;

            if (IsQuoted(value))
            {
                quoted = true;
                value  = RemoveQuotes(value);
            }
            string escapedValue = Uri.EscapeDataString(value);

            // Normal cookie
            if (!ChunkSize.HasValue || ChunkSize.Value > prefix.Length + escapedValue.Length + suffix.Length + (quoted ? 2 : 0))
            {
                var cookie = new HttpCookie(escapedKey, escapedValue);
                SetOptions(cookie, options, domainHasValue, pathHasValue, expiresHasValue);

                webContext.Response.AppendCookie(cookie);
            }
            else if (ChunkSize.Value < prefix.Length + suffix.Length + (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=/
                int dataSizePerCookie = ChunkSize.Value - prefix.Length - suffix.Length - (quoted ? 2 : 0) - 3; // Budget 3 chars for the chunkid.
                int cookieChunkCount  = (int)Math.Ceiling(escapedValue.Length * 1.0 / dataSizePerCookie);

                var cookie = new HttpCookie(escapedKey, "chunks:" + cookieChunkCount.ToString(CultureInfo.InvariantCulture));
                SetOptions(cookie, options, domainHasValue, pathHasValue, expiresHasValue);

                webContext.Response.AppendCookie(cookie);

                int offset = 0;
                for (int chunkId = 1; chunkId <= cookieChunkCount; chunkId++)
                {
                    int    remainingLength = escapedValue.Length - offset;
                    int    length          = Math.Min(dataSizePerCookie, remainingLength);
                    string segment         = escapedValue.Substring(offset, length);
                    offset += length;

                    cookie = new HttpCookie(escapedKey + "C" + chunkId.ToString(CultureInfo.InvariantCulture), quoted ? Quote(segment) : segment);
                    SetOptions(cookie, options, domainHasValue, pathHasValue, expiresHasValue);

                    webContext.Response.AppendCookie(cookie);
                }
            }
        }
 public void DeleteCookie(IOwinContext context, string key, CookieOptions options)
 {
     CheckSameSite(context, options);
     _innerManager.DeleteCookie(context, key, options);
 }
Ejemplo n.º 7
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string token = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("token");
                if (values != null && values.Count == 1)
                {
                    token = values[0];
                }

                string stateCookieKey = Constants.StatePrefix + Options.AuthenticationType;
                string stateCookie    = Request.Cookies[stateCookieKey];
                if (string.IsNullOrWhiteSpace(stateCookie))
                {
                    _logger.WriteWarning("{0} cookie not found.", stateCookie);
                    return(null);
                }

                var cookieOptions = new CookieOptions
                {
                    HttpOnly = true,
                    Secure   = Request.IsSecure
                };

                Response.Cookies.Delete(stateCookieKey, cookieOptions);

                properties = Options.StateDataFormat.Unprotect(stateCookie);
                if (properties == null)
                {
                    return(null);
                }

                // Request the token
                ActivityDetails activityDetails = await _yotiClient.GetActivityDetailsAsync(token);

                if (activityDetails.Outcome != ActivityOutcome.Success)
                {
                    // TODO: Check how this is handled
                    throw new HttpRequestException();
                }

                var context = new YotiAuthenticatedContext(Context, activityDetails.UserProfile);

                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);

                if (!string.IsNullOrEmpty(context.User.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.User.Id, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (context.User.Selfie != null)
                {
                    context.Identity.AddClaim(new Claim("selfie", Convert.ToBase64String(context.User.Selfie.Data), context.User.Selfie.Type.ToString(), Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.GivenNames))
                {
                    context.Identity.AddClaim(new Claim("given_names", context.User.GivenNames, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.FamilyName))
                {
                    context.Identity.AddClaim(new Claim("family_name", context.User.FamilyName, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.MobileNumber))
                {
                    context.Identity.AddClaim(new Claim("phone_number", context.User.MobileNumber, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.EmailAddress))
                {
                    context.Identity.AddClaim(new Claim("email_address", context.User.EmailAddress, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (context.User.DateOfBirth != null)
                {
                    context.Identity.AddClaim(new Claim("date_of_birth", context.User.DateOfBirth.Value.ToString("yyyy-MM-dd"), ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.Address))
                {
                    context.Identity.AddClaim(new Claim("postal_address", context.User.Address, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.Gender))
                {
                    context.Identity.AddClaim(new Claim("gender", context.User.Gender, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.Nationality))
                {
                    context.Identity.AddClaim(new Claim("nationality", context.User.Nationality, ClaimValueTypes.String, Options.AuthenticationType));
                }

                foreach (var attributeName in context.User.OtherAttributes.Keys)
                {
                    var attributeValue = context.User.OtherAttributes[attributeName];
                    context.Identity.AddClaim(new Claim(attributeName, attributeValue.ToString(), attributeValue.Type.ToString(), Options.AuthenticationType));
                }

                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
 public AppendCookieContext(HttpContext context, CookieOptions options, string name, string value)
 {
 }
Ejemplo n.º 9
0
        CookieContainer BuildCookieContainer(CookieOptions cookieOptions, CookieCollection insertCookie)
        {
            if (cookieOptions.HasFlag(CookieOptions.NoCookies))
                return null;

            CookieContainer container = null;
            if (cookieOptions.HasFlag(CookieOptions.UseShared))
            {
                container = _sharedCookies;
            }
            else
            {
                container = new CookieContainer();
            }
            if (insertCookie != null)
                container.Add(insertCookie);

            return container;
        }
Ejemplo n.º 10
0
 public void Append(string key, string value, CookieOptions options)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 11
0
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            MethodInfo method = GetMethod(context.RouteData.Values["action"].ToString());

            if (method.ReturnType.Equals(typeof(IActionResult)) == false)
            {
                if (method.ReturnType.Equals(typeof(ReturnData)) == false)
                {
                    if (context.Result == null)
                    {
                        if (context.Exception != null)
                        {
                            context.Result = Json(new ReturnData {
                                isError = true, data = new GenericError(context.Exception)
                            });
                            Log.Error(this, method.Name, context.Exception);
                        }
                        else
                        {
                            context.Result = Json(new ReturnData {
                                data = null
                            });
                        }
                    }
                    else
                    {
                        if (context.Result is ObjectResult)
                        {
                            try
                            {
                                if (((ObjectResult)context.Result).Value is ReturnData)
                                {
                                    context.Result = Json(((ObjectResult)context.Result).Value);
                                }
                                else
                                {
                                    context.Result = Json(new ReturnData {
                                        data = ((ObjectResult)context.Result).Value
                                    });
                                }
                            }
                            catch (Exception ex)
                            {
                                context.Result = Json(new ReturnData {
                                    isError = true, data = new GenericError(ex)
                                });
                                Log.Error(this, method.Name, ex);
                            }
                        }
                    }
                }
            }

            ///
            /// Mantiene el Idioma seleccionado por cookies
            ///
            CookieOptions options = new CookieOptions();

            options.Expires = DateTime.Now.AddDays(1);
            context.HttpContext.Response.Cookies.Append(".AspNetCore.Culture", "c=" + System.Globalization.CultureInfo.CurrentCulture.Name + "|uic=" + System.Globalization.CultureInfo.CurrentCulture.Name, options);

            base.OnActionExecuted(context);
        }
Ejemplo n.º 12
0
        private string GetXml(CookieOptions cookieOptions)
        {
            StringBuilder personInfoXml = new StringBuilder(128);

            XmlWriterSettings settings = SDKHelper.XmlUnicodeWriterSettings;

            using (XmlWriter writer = XmlWriter.Create(personInfoXml, settings))
            {
                WriteXml("person-info", writer, cookieOptions);
                writer.Flush();
            }
            return personInfoXml.ToString();
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Gets the XML representation of the <see cref="PersonInfo"/>
 /// that is appropriate for storing in the cookie.
 /// </summary>
 /// 
 /// <returns>
 /// A XML string containing the person information.
 /// </returns>
 /// 
 /// <remarks>
 /// Embedded url will be overridden with the configuration value.
 /// </remarks>
 /// 
 internal string GetXmlForCookie(CookieOptions cookieOptions)
 {
     return GetXml(cookieOptions);
 }
Ejemplo n.º 14
0
        protected void GenerateCorrelationId(AuthenticationProperties properties)
        {
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }

            string correlationKey = Constants.CorrelationPrefix + BaseOptions.AuthenticationType;

            var nonceBytes = new byte[32];
            Random.GetBytes(nonceBytes);
            string correlationId = TextEncodings.Base64Url.Encode(nonceBytes);

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure = Request.IsSecure
            };

            properties.Dictionary[correlationKey] = correlationId;

            Response.Cookies.Append(correlationKey, correlationId, cookieOptions);
        }
Ejemplo n.º 15
0
        protected bool ValidateCorrelationId(AuthenticationProperties properties, ILogger logger)
        {
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }

            string correlationKey = Constants.CorrelationPrefix + BaseOptions.AuthenticationType;

            string correlationCookie = Request.Cookies[correlationKey];
            if (string.IsNullOrWhiteSpace(correlationCookie))
            {
                logger.WriteWarning("{0} cookie not found.", correlationKey);
                return false;
            }

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure = Request.IsSecure
            };

            Response.Cookies.Delete(correlationKey, cookieOptions);

            string correlationExtra;
            if (!properties.Dictionary.TryGetValue(
                correlationKey,
                out correlationExtra))
            {
                logger.WriteWarning("{0} state property not found.", correlationKey);
                return false;
            }

            properties.Dictionary.Remove(correlationKey);

            if (!string.Equals(correlationCookie, correlationExtra, StringComparison.Ordinal))
            {
                logger.WriteWarning("{0} correlation cookie and state property mismatch.", correlationKey);
                return false;
            }

            return true;
        }
Ejemplo n.º 16
0
        HttpWebRequest CreateRequest(Uri uri, CookieOptions cookieOptions, TimingParams param, RequestParams requestParam, RatedProxy proxy, CookieCollection insertCookie)
        {
            HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;

            request.Headers = requestParam.Headers;
            request.UserAgent = requestParam.UserAgent;
            request.Host = uri.Host;
            request.Accept = requestParam.Accept;
            request.ContentType = requestParam.ContentType;
            //request.Referer = "http://www.google.com/";
            request.AllowAutoRedirect = requestParam.UseRedirect;
            request.KeepAlive = requestParam.KeepAlive;
            request.AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip;
            request.Proxy = proxy;
            request.Timeout = param.RequestTimeout;
            request.ReadWriteTimeout = param.GetStreamTimeout;
            request.CookieContainer = BuildCookieContainer(cookieOptions, insertCookie);
            request.Method = requestParam.Method;

            return request;
        }
Ejemplo n.º 17
0
        /// <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([NotNull] HttpContext context, [NotNull] string key, [NotNull] CookieOptions options)
        {
            var escapedKey = Encoder.UrlEncode(key);
            var keys       = new List <string>();

            keys.Add(escapedKey + "=");

            var requestCookie = context.Request.Cookies[key];
            var chunks        = ParseChunksCount(requestCookie);

            if (chunks > 0)
            {
                for (int i = 1; i <= chunks + 1; i++)
                {
                    var subkey = escapedKey + "C" + 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.GetValues(Constants.Headers.SetCookie);

            if (existingValues != null)
            {
                responseHeaders.SetValues(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),
                });
            }
        }
Ejemplo n.º 18
0
        private void WriteXml(string nodeName, XmlWriter writer, CookieOptions cookieOptions)
        {
            bool writeContainingNode = false;
            if (!String.IsNullOrEmpty(nodeName))
            {
                writeContainingNode = true;
                writer.WriteStartElement(nodeName);
            }

            writer.WriteElementString("person-id", _personId.ToString());
            writer.WriteElementString("name", _name);

            if (_appSettings != null)
            {
                if ((cookieOptions & CookieOptions.MinimizeApplicationSettings) == 0)
                {
                    writer.WriteRaw(_appSettings.CreateNavigator().OuterXml);
                }
                else
                {
                    writer.WriteElementString("more-app-settings", String.Empty);
                }
            }
            else if (_moreAppSettings)
            {
                writer.WriteElementString("more-app-settings", String.Empty);
            }

            if (_selectedRecordId != Guid.Empty)
            {
                writer.WriteElementString(
                    "selected-record-id",
                    _selectedRecordId.ToString());
            }

            writer.WriteStartElement("connection");

            writer.WriteElementString(
                "app-id",
                _connection.ApplicationId.ToString());

            if ((cookieOptions & CookieOptions.IncludeUrl) != 0)
            {
                writer.WriteElementString(
                    "wildcat-url",
                    _connection.RequestUrl.ToString());
            }

            AuthenticatedConnection authConnection = _connection as AuthenticatedConnection;
            if (authConnection != null && authConnection.Credential != null)
            {
                writer.WriteStartElement("credential");
                authConnection.Credential.WriteCookieXml(writer);
                writer.WriteEndElement();
            }

            if (!String.IsNullOrEmpty(_connection.RequestCompressionMethod))
            {
                writer.WriteElementString(
                    "request-compression-method",
                    _connection.RequestCompressionMethod);
            }

            writer.WriteEndElement();

                // If we are removing records because they make the cookie too big, we remove all except
                // the currently-selected record...
            bool skippedRecords = false;
            foreach (HealthRecordInfo record in AuthorizedRecords.Values)
            {
                if ((cookieOptions & CookieOptions.MinimizeRecords) == 0)
                {
                    record.WriteXml("record", writer);
                }
                else
                {
                    if (_selectedRecordId != Guid.Empty &&
                        record.Id == _selectedRecordId)
                    {
                        record.WriteXml("record", writer);
                    }
                    else
                    {
                        skippedRecords = true;
                    }
                }
            }

            if (skippedRecords || _moreRecords)
            {
                writer.WriteElementString("more-records", String.Empty);
            }

            if (!String.IsNullOrEmpty(_preferredCulture))
            {
                WriteCulture("preferred-culture", writer, _preferredCulture);
            }

            if (!String.IsNullOrEmpty(_preferredUICulture))
            {
                WriteCulture("preferred-uiculture", writer, _preferredUICulture);
            }

            if (writeContainingNode)
            {
                writer.WriteEndElement();
            }
        }
        public static void SetStateData(this IResponseCookies responseCookies, string key, Dictionary <string, string> dictionary, CookieOptions cookieOptions)
        {
            if (responseCookies == null)
            {
                throw new ArgumentNullException(nameof(responseCookies));
            }

            responseCookies.Append(key, JsonSerializer.Serialize(dictionary), cookieOptions);
        }
Ejemplo n.º 20
0
        /// <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(IOwinContext context, string key, CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            string escapedKey = Uri.EscapeDataString(key);
            List<string> keys = new List<string>();
            keys.Add(escapedKey + "=");

            string requestCookie = context.Request.Cookies[key];
            int chunks = ParseChunksCount(requestCookie);
            if (chunks > 0)
            {
                for (int i = 1; i <= chunks + 1; i++)
                {
                    string subkey = escapedKey + "C" + i.ToString(CultureInfo.InvariantCulture);
                    keys.Add(subkey + "=");
                }
            }

            bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
            bool 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);
            }

            IHeaderDictionary responseHeaders = context.Response.Headers;
            IList<string> existingValues = responseHeaders.GetValues(Constants.Headers.SetCookie);
            if (existingValues != null)
            {
                responseHeaders.SetValues(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),
                    });
            }
        }
Ejemplo n.º 21
0
 public void Append(string key, string value, CookieOptions options)
 {
     cookies.Add(key, new Cookie(key, value, options.Path, options.Domain));
 }
Ejemplo n.º 22
0
        public async Task <IActionResult> CalcularFrete(string cepDestino)
        {
            try
            {
                Frete frete   = _cookieValorPrazoFrete.Consultar().Where(a => a.CEP == cepDestino && a.CarrinhoId == HashGenerator.CreateMD5(JsonConvert.SerializeObject(_carrinhoCompra.Consultar()))).FirstOrDefault();
                var   options = new CookieOptions()
                {
                    Expires = DateTime.Now.AddDays(7), IsEssential = true
                };

                HttpContext.Response.Cookies.Append("Carrinho.CEP", cepDestino, options);
                if (frete != null)
                {
                    return(Ok(frete));
                }
                else
                {
                    List <ProdutoItem> produtos = CarregarProdutoDB();
                    List <Pacote>      pacotes  = _pacote.CalcularPacote(produtos);

                    ValorPrazoFrete valorPAC = await _frete.CalcularFrete(cepDestino, TipoFreteConstant.PAC, pacotes);

                    ValorPrazoFrete valorSEDEX = await _frete.CalcularFrete(cepDestino, TipoFreteConstant.Sedex, pacotes);

                    ValorPrazoFrete valorSEDEX10 = await _frete.CalcularFrete(cepDestino, TipoFreteConstant.Sedex10, pacotes);

                    List <ValorPrazoFrete> lista = new List <ValorPrazoFrete>();
                    if (valorPAC != null)
                    {
                        lista.Add(valorPAC);
                    }
                    if (valorSEDEX != null)
                    {
                        lista.Add(valorSEDEX);
                    }
                    if (valorSEDEX10 != null)
                    {
                        lista.Add(valorSEDEX10);
                    }

                    if (lista.Count() == 0)
                    {
                        return(BadRequest(new { erro = "Este CEP não possui acesso ao servico dos CORREIOS" }));;
                    }

                    frete = new Frete()
                    {
                        CEP        = cepDestino,
                        CarrinhoId = HashGenerator.CreateMD5(JsonConvert.SerializeObject(_carrinhoCompra.Consultar())),
                        Valores    = lista
                    };

                    _cookieValorPrazoFrete.Cadastrar(frete);

                    return(Ok(frete));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(e));
            }
        }
Ejemplo n.º 23
0
 public ParsedCookie(CookieOptions cookieOptions, string name, string value)
 {
     CookieOptions = cookieOptions;
     Name          = name;
     Value         = value;
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Sets an expired cookie
        /// </summary>
        /// <param name="key"></param>
        /// <param name="options"></param>
        public void Delete(string key, CookieOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var encodedKeyPlusEquals = UrlEncoder.Default.UrlEncode(key) + "=";
            bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
            bool pathHasValue = !string.IsNullOrEmpty(options.Path);

            Func<string, bool> rejectPredicate;
            if (domainHasValue)
            {
                rejectPredicate = value =>
                    value.StartsWith(encodedKeyPlusEquals, StringComparison.OrdinalIgnoreCase) &&
                        value.IndexOf("domain=" + options.Domain, StringComparison.OrdinalIgnoreCase) != -1;
            }
            else if (pathHasValue)
            {
                rejectPredicate = value =>
                    value.StartsWith(encodedKeyPlusEquals, StringComparison.OrdinalIgnoreCase) &&
                        value.IndexOf("path=" + options.Path, StringComparison.OrdinalIgnoreCase) != -1;
            }
            else
            {
                rejectPredicate = value => value.StartsWith(encodedKeyPlusEquals, StringComparison.OrdinalIgnoreCase);
            }

            var existingValues = Headers[HeaderNames.SetCookie];
            if (!StringValues.IsNullOrEmpty(existingValues))
            {
                Headers[HeaderNames.SetCookie] = existingValues.Where(value => !rejectPredicate(value)).ToArray();
            }

            Append(key, string.Empty, new CookieOptions
            {
                Path = options.Path,
                Domain = options.Domain,
                Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
            });
        }
        public static void SetCookie(this IAbpAntiForgeryManager manager, HttpContext context, IIdentity identity = null, CookieOptions cookieOptions = null)
        {
            if (identity != null)
            {
                context.User = new ClaimsPrincipal(identity);
            }

            if (cookieOptions != null)
            {
                context.Response.Cookies.Append(manager.Configuration.TokenCookieName, manager.GenerateToken(), cookieOptions);
            }
            else
            {
                context.Response.Cookies.Append(manager.Configuration.TokenCookieName, manager.GenerateToken());
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Sets an expired cookie
        /// </summary>
        /// <param name="key"></param>
        /// <param name="options"></param>
        public void Delete(string key, CookieOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            
            var encodedKeyPlusEquals = UrlEncoder.Default.Encode(key) + "=";
            bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
            bool pathHasValue = !string.IsNullOrEmpty(options.Path);

            Func<string, string, CookieOptions, bool> rejectPredicate;
            if (domainHasValue)
            {
                rejectPredicate = (value, encKeyPlusEquals, opts) =>
                    value.StartsWith(encKeyPlusEquals, StringComparison.OrdinalIgnoreCase) &&
                        value.IndexOf($"domain={opts.Domain}", StringComparison.OrdinalIgnoreCase) != -1;
            }
            else if (pathHasValue)
            {
                rejectPredicate = (value, encKeyPlusEquals, opts) =>
                    value.StartsWith(encKeyPlusEquals, StringComparison.OrdinalIgnoreCase) &&
                        value.IndexOf($"path={opts.Path}", StringComparison.OrdinalIgnoreCase) != -1;
            }
            else
            {
                rejectPredicate = (value, encKeyPlusEquals, opts) => value.StartsWith(encKeyPlusEquals, StringComparison.OrdinalIgnoreCase);
            }

            var existingValues = Headers[HeaderNames.SetCookie];
            if (!StringValues.IsNullOrEmpty(existingValues))
            {
                var values = existingValues.ToArray();
                var newValues = new List<string>();

                for (var i = 0; i < values.Length; i++)
                {
                    if (!rejectPredicate(values[i], encodedKeyPlusEquals, options))
                    {
                        newValues.Add(values[i]);
                    }
                }
                
                Headers[HeaderNames.SetCookie] = new StringValues(newValues.ToArray());
            }

            Append(key, string.Empty, new CookieOptions
            {
                Path = options.Path,
                Domain = options.Domain,
                Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
            });
        }
 public DeleteCookieContext(HttpContext context, CookieOptions options, string name)
 {
 }
Ejemplo n.º 28
0
        /// <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(IOwinContext 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 domainHasValue = !string.IsNullOrEmpty(options.Domain);
            var pathHasValue = !string.IsNullOrEmpty(options.Path);
            var expiresHasValue = options.Expires.HasValue;

            var templateLength = key.Length + "=".Length
                + (domainHasValue ? "; domain=".Length + options.Domain.Length : 0)
                + (pathHasValue ? "; path=".Length + options.Path.Length : 0)
                + (expiresHasValue ? "; expires=ddd, dd-MMM-yyyy HH:mm:ss GMT".Length : 0)
                + (options.Secure ? "; secure".Length : 0)
                + (options.HttpOnly ? "; HttpOnly".Length : 0);

            // 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("The cookie key and options are larger than ChunksSize, leaving no room for data.");
            }
            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);
                }
            }
        }
        private static void CheckSameSiteBackwardsCompatiblity(HttpContext httpContext, CookieOptions options)
        {
            var userAgent = httpContext.Request.Headers["User-Agent"].ToString();

            if (options.SameSite == SameSiteMode.None)
            {
                if (String.IsNullOrEmpty(userAgent))
                {
                    return;
                }

                // Cover all iOS based browsers here. This includes:
                // - Safari on iOS 12 for iPhone, iPod Touch, iPad
                // - WkWebview on iOS 12 for iPhone, iPod Touch, iPad
                // - Chrome on iOS 12 for iPhone, iPod Touch, iPad
                // All of which are broken by SameSite=None, because they use the iOS networking stack
                if (userAgent.Contains("CPU iPhone OS 12") || userAgent.Contains("iPad; CPU OS 12"))
                {
                    options.SameSite = AspNetCore.Http.SameSiteMode.Unspecified;
                    return;
                }

                // Cover Mac OS X based browsers that use the Mac OS networking stack. This includes:
                // - Safari on Mac OS X.
                // This does not include:
                // - Chrome on Mac OS X
                // Because they do not use the Mac OS networking stack.
                if (userAgent.Contains("Macintosh; Intel Mac OS X 10_14") &&
                    userAgent.Contains("Version/") && userAgent.Contains("Safari"))
                {
                    options.SameSite = AspNetCore.Http.SameSiteMode.Unspecified;
                    return;
                }

                // Cover Chrome 50-69, because some versions are broken by SameSite=None,
                // and none in this range require it.
                // Note: this covers some pre-Chromium Edge versions,
                // but pre-Chromium Edge does not require SameSite=None.
                if (userAgent.Contains("Chrome/5") || userAgent.Contains("Chrome/6"))
                {
                    options.SameSite = AspNetCore.Http.SameSiteMode.Unspecified;
                }
            }
        }
Ejemplo n.º 30
0
        /// <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(IOwinContext 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;
            string[] existingValues;
            if (responseHeaders.TryGetValue(Constants.Headers.SetCookie, out existingValues) && existingValues != null)
            {
                responseHeaders.SetValues(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),
                    });
            }
        }
 public void AppendResponseCookie(IOwinContext context, string key, string value,
                                  CookieOptions options)
 {
     CheckSameSite(context, options);
     _innerManager.AppendResponseCookie(context, key, value, options);
 }
Ejemplo n.º 32
0
        protected void GenerateCorrelationId(AuthenticationExtra extra)
        {
            var correlationKey = Constants.CorrelationPrefix + BaseOptions.AuthenticationType;

            var nonceBytes = new byte[32];
            Random.GetBytes(nonceBytes);
            var correlationId = TextEncodings.Base64Url.Encode(nonceBytes);

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure = Request.IsSecure
            };

            extra.Properties[correlationKey] = correlationId;

            Response.AddCookie(correlationKey, correlationId, cookieOptions);
        }
Ejemplo n.º 33
0
        public async Task <IActionResult> OnPostPhase3Async()
        {
            LoggedIn               = !string.IsNullOrEmpty(Request.Cookies["Name"]);
            LastError              = "";
            SignupPhase1           = false;
            SignupVerifyEmailPhase = false;
            SignupFinalPhase       = true;

            if (FinalViewModel.Password != FinalViewModel.PasswordConfirmation)
            {
                LastError = "گذرواژه و تکرار آن یکی نیستند.";
                return(Page());
            }

            VerifiedSignUpViewModel postViewModel = new VerifiedSignUpViewModel()
            {
                Email     = FinalViewModel.Email,
                Secret    = FinalViewModel.Secret,
                FirstName = FinalViewModel.FirstName,
                SureName  = FinalViewModel.SureName,
                Password  = FinalViewModel.Password
            };

            var response = await _httpClient.PostAsync($"{APIRoot.Url}/api/users/finalizesignup", new StringContent(JsonConvert.SerializeObject(postViewModel), Encoding.UTF8, "application/json"));

            if (!response.IsSuccessStatusCode)
            {
                LastError = JsonConvert.DeserializeObject <string>(await response.Content.ReadAsStringAsync());
                return(Page());
            }


            LoginViewModel loginViewModel = new LoginViewModel()
            {
                ClientAppName = "وبگاه گنجور",
                Language      = "fa-IR",
                Username      = postViewModel.Email,
                Password      = postViewModel.Password
            };

            var stringContent = new StringContent(JsonConvert.SerializeObject(loginViewModel), Encoding.UTF8, "application/json");
            var loginUrl      = $"{APIRoot.Url}/api/users/login";

            response = await _httpClient.PostAsync(loginUrl, stringContent);

            if (!response.IsSuccessStatusCode)
            {
                LastError = JsonConvert.DeserializeObject <string>(await response.Content.ReadAsStringAsync());
                return(Page());
            }

            LoggedOnUserModelEx loggedOnUser = JsonConvert.DeserializeObject <LoggedOnUserModelEx>(await response.Content.ReadAsStringAsync());

            var cookieOption = new CookieOptions()
            {
                Expires = DateTime.Now.AddDays(365),
            };

            Response.Cookies.Append("UserId", loggedOnUser.User.Id.ToString(), cookieOption);
            Response.Cookies.Append("SessionId", loggedOnUser.SessionId.ToString(), cookieOption);
            Response.Cookies.Append("Token", loggedOnUser.Token, cookieOption);
            Response.Cookies.Append("Username", loggedOnUser.User.Username, cookieOption);
            Response.Cookies.Append("Name", $"{loggedOnUser.User.FirstName} {loggedOnUser.User.SureName}", cookieOption);
            Response.Cookies.Append("NickName", $"{loggedOnUser.User.NickName}", cookieOption);
            Response.Cookies.Append("KeepHistory", $"{loggedOnUser.KeepHistory}", cookieOption);

            bool canEditContent = false;
            var  ganjoorEntity  = loggedOnUser.SecurableItem.Where(s => s.ShortName == RMuseumSecurableItem.GanjoorEntityShortName).SingleOrDefault();

            if (ganjoorEntity != null)
            {
                var op = ganjoorEntity.Operations.Where(o => o.ShortName == SecurableItem.ModifyOperationShortName).SingleOrDefault();
                if (op != null)
                {
                    canEditContent = op.Status;
                }
            }

            Response.Cookies.Append("CanEdit", canEditContent.ToString(), cookieOption);



            return(Redirect($"{_configuration["SiteUrl"]}/User"));
        }
Ejemplo n.º 34
0
 public DeleteCookieContext(HttpContext context, CookieOptions options, string name)
 {
     Context       = context;
     CookieOptions = options;
     CookieName    = name;
 }
Ejemplo n.º 35
0
        /// <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([NotNull] HttpContext context, [NotNull] string key, string value, [NotNull] CookieOptions options)
        {
            var escapedKey = Encoder.UrlEncode(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.UrlEncode(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.AppendValues(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.AppendValues(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.AppendValues(Constants.Headers.SetCookie, chunks);
            }
        }
Ejemplo n.º 36
0
        public async Task <PageResult> OnGetAsync(string academicYear)
        {
            CookieOptions option = new CookieOptions();

            option.Expires = DateTime.Now.AddMinutes(60);
            Response.Cookies.Append("CookieTest", "Testing", option);

            string applicationData = Request.Cookies["ApplicationData"];

            byte[] decodedBytes     = Convert.FromBase64String(applicationData);
            string decodedString    = ASCIIEncoding.ASCII.GetString(decodedBytes);
            var    jApplicationData = JObject.Parse(decodedString);

            CookieTest = decodedString;
            //CookieTest = jApplicationData.GetValue("Application.Title").ToString();

            //Application = new Application
            //{
            //    Forename = "Robin"
            //};

            Application = CookieFunctions.GetApplicationCookieValues(Request);

            string selectListDomain = null;

            selectListDomain = "TITLE";
            TitleData        = await _context.SelectListData
                               .FromSqlInterpolated($"EXEC SPR_OLA_SelectListData @Domain={selectListDomain}")
                               .AsNoTracking()
                               .ToListAsync();

            ViewData["TitleID"] = new SelectList(TitleData, "Code", "Description");

            selectListDomain = "GENDER";
            GenderData       = await _context.SelectListData
                               .FromSqlInterpolated($"EXEC SPR_OLA_SelectListData @Domain={selectListDomain}")
                               .AsNoTracking()
                               .ToListAsync();

            ViewData["GenderID"] = new SelectList(GenderData, "Code", "Description");

            selectListDomain = "VISA";
            VisaData         = await _context.SelectListData
                               .FromSqlInterpolated($"EXEC SPR_OLA_SelectListData @Domain={selectListDomain}")
                               .AsNoTracking()
                               .ToListAsync();

            ViewData["VisaTypeID"] = new SelectList(VisaData, "Code", "Description");

            selectListDomain = "SCHOOL";
            SchoolData       = await _context.SelectListData
                               .FromSqlInterpolated($"EXEC SPR_OLA_SelectListData @Domain={selectListDomain}")
                               .AsNoTracking()
                               .ToListAsync();

            ViewData["SchoolID"] = new SelectList(SchoolData, "Code", "Description");

            selectListDomain = "ETHNIC_GROUP";
            EthnicGroupData  = await _context.SelectListData
                               .FromSqlInterpolated($"EXEC SPR_OLA_SelectListData @Domain={selectListDomain}")
                               .AsNoTracking()
                               .ToListAsync();

            ViewData["EthnicGroupID"] = new SelectList(EthnicGroupData, "Code", "Description");

            selectListDomain       = "DISABILITY_CATEGORY";
            DisabilityCategoryData = await _context.SelectListData
                                     .FromSqlInterpolated($"EXEC SPR_OLA_SelectListData @Domain={selectListDomain}")
                                     .AsNoTracking()
                                     .ToListAsync();

            ViewData["DisabilityCategoryID"] = new SelectList(DisabilityCategoryData, "Code", "Description");

            selectListDomain = "QOE";
            QOEData          = await _context.SelectListData
                               .FromSqlInterpolated($"EXEC SPR_OLA_SelectListData @Domain={selectListDomain}")
                               .AsNoTracking()
                               .ToListAsync();

            ViewData["QOEID"] = new SelectList(QOEData, "Code", "Description");

            selectListDomain = "GRADE";
            GradeData        = await _context.SelectListData
                               .FromSqlInterpolated($"EXEC SPR_OLA_SelectListData @Domain={selectListDomain}")
                               .AsNoTracking()
                               .ToListAsync();

            ViewData["GradeID"] = new SelectList(GradeData, "Code", "Description");

            return(Page());
        }
Ejemplo n.º 37
0
        protected override async Task <AuthenticationTicket> HandleAuthenticateAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                var query = Request.Query;
                var protectedRequestToken = Request.Cookies[StateCookie];

                var requestToken = Options.StateDataFormat.Unprotect(protectedRequestToken);

                if (requestToken == null)
                {
                    Logger.LogWarning("Invalid state");
                    return(null);
                }

                properties = requestToken.Properties;

                var returnedToken = query["oauth_token"];
                if (StringValues.IsNullOrEmpty(returnedToken))
                {
                    Logger.LogWarning("Missing oauth_token");
                    return(new AuthenticationTicket(properties, Options.AuthenticationScheme));
                }

                if (!string.Equals(returnedToken, requestToken.Token, StringComparison.Ordinal))
                {
                    Logger.LogWarning("Unmatched token");
                    return(new AuthenticationTicket(properties, Options.AuthenticationScheme));
                }

                var oauthVerifier = query["oauth_verifier"];
                if (StringValues.IsNullOrEmpty(oauthVerifier))
                {
                    Logger.LogWarning("Missing or blank oauth_verifier");
                    return(new AuthenticationTicket(properties, Options.AuthenticationScheme));
                }

                var cookieOptions = new CookieOptions
                {
                    HttpOnly = true,
                    Secure   = Request.IsHttps
                };

                Response.Cookies.Delete(StateCookie, cookieOptions);

                var accessToken = await ObtainAccessTokenAsync(Options.ConsumerKey, Options.ConsumerSecret, requestToken, oauthVerifier);

                var identity = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, accessToken.UserId, ClaimValueTypes.String, Options.ClaimsIssuer),
                    new Claim(ClaimTypes.Name, accessToken.ScreenName, ClaimValueTypes.String, Options.ClaimsIssuer),
                    new Claim("urn:twitter:userid", accessToken.UserId, ClaimValueTypes.String, Options.ClaimsIssuer),
                    new Claim("urn:twitter:screenname", accessToken.ScreenName, ClaimValueTypes.String, Options.ClaimsIssuer)
                },
                                                  Options.ClaimsIssuer);

                if (Options.SaveTokensAsClaims)
                {
                    identity.AddClaim(new Claim("access_token", accessToken.Token, ClaimValueTypes.String, Options.ClaimsIssuer));
                }

                return(await CreateTicketAsync(identity, properties, accessToken));
            }
            catch (Exception ex)
            {
                Logger.LogError("Authentication failed", ex);
                return(new AuthenticationTicket(properties, Options.AuthenticationScheme));
            }
        }
Ejemplo n.º 38
0
 public static void SetObjectAsJson(this HttpResponse response, string key, object value, CookieOptions options)
 {
     response.Cookies.Append(key, JsonConvert.SerializeObject(value), options);
 }
Ejemplo n.º 39
0
        public async Task <IActionResult> OnGetAsync()
        {
            if (string.IsNullOrEmpty(Request.Cookies["Token"]))
            {
                return(Redirect("/"));
            }
            LastError = "";
            using (HttpClient secureClient = new HttpClient())
                if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response))
                {
                    var response = await secureClient.GetAsync($"{APIRoot.Url}/api/options/KeepHistory");

                    if (!response.IsSuccessStatusCode)
                    {
                        LastError = JsonConvert.DeserializeObject <string>(await response.Content.ReadAsStringAsync());
                        return(Page());
                    }
                    TrackingIsEnabled = JsonConvert.DeserializeObject <string>(await response.Content.ReadAsStringAsync()) == true.ToString();

                    bool keepHistory = Request.Cookies["KeepHistory"] == "True";
                    if (keepHistory != TrackingIsEnabled)
                    {
                        if (Request.Cookies["KeepHistory"] != null)
                        {
                            Response.Cookies.Delete("KeepHistory");
                        }
                        var cookieOption = new CookieOptions()
                        {
                            Expires = DateTime.Now.AddDays(365),
                        };
                        Response.Cookies.Append("KeepHistory", $"{TrackingIsEnabled}", cookieOption);
                    }

                    int pageNumber = 1;
                    if (!string.IsNullOrEmpty(Request.Query["page"]))
                    {
                        pageNumber = int.Parse(Request.Query["page"]);
                    }
                    var responseHistoryItems = await secureClient.GetAsync($"{APIRoot.Url}/api/tracking/?PageNumber={pageNumber}&PageSize=20");

                    if (!responseHistoryItems.IsSuccessStatusCode)
                    {
                        LastError = JsonConvert.DeserializeObject <string>(await responseHistoryItems.Content.ReadAsStringAsync());
                        return(Page());
                    }

                    HistoryItems = JArray.Parse(await responseHistoryItems.Content.ReadAsStringAsync()).ToObject <List <GanjoorUserBookmarkViewModel> >();

                    string paginnationMetadata = responseHistoryItems.Headers.GetValues("paging-headers").FirstOrDefault();
                    if (!string.IsNullOrEmpty(paginnationMetadata))
                    {
                        PaginationMetadata paginationMetadata = JsonConvert.DeserializeObject <PaginationMetadata>(paginnationMetadata);
                        PaginationLinks = new List <NameIdUrlImage>();
                        if (paginationMetadata.totalPages > 1)
                        {
                            if (paginationMetadata.currentPage > 3)
                            {
                                PaginationLinks.Add
                                (
                                    new NameIdUrlImage()
                                {
                                    Name = "صفحهٔ اول",
                                    Url  = "/User/History/?page=1"
                                }
                                );
                            }
                            for (int i = (paginationMetadata.currentPage - 2); i <= (paginationMetadata.currentPage + 2); i++)
                            {
                                if (i >= 1 && i <= paginationMetadata.totalPages)
                                {
                                    if (i == paginationMetadata.currentPage)
                                    {
                                        PaginationLinks.Add
                                        (
                                            new NameIdUrlImage()
                                        {
                                            Name = i.ToPersianNumbers(),
                                        }
                                        );
                                    }
                                    else
                                    {
                                        PaginationLinks.Add
                                        (
                                            new NameIdUrlImage()
                                        {
                                            Name = i.ToPersianNumbers(),
                                            Url  = $"/User/History/?page={i}"
                                        }
                                        );
                                    }
                                }
                            }
                            if (paginationMetadata.totalPages > (paginationMetadata.currentPage + 2))
                            {
                                PaginationLinks.Add
                                (
                                    new NameIdUrlImage()
                                {
                                    Name = "... ",
                                }
                                );

                                PaginationLinks.Add
                                (
                                    new NameIdUrlImage()
                                {
                                    Name = "صفحهٔ آخر",
                                    Url  = $"/User/History/?page={paginationMetadata.totalPages}"
                                }
                                );
                            }
                        }
                    }
                }
                else
                {
                    LastError = "لطفا از گنجور خارج و مجددا به آن وارد شوید.";
                }
            return(Page());
        }
Ejemplo n.º 40
0
        public static void SetCookie(this HttpContext httpContext, string key, string value, CookieOptions options = null)
        {
            if (httpContext == null)
            {
                return;
            }
            if (httpContext.Response == null)
            {
                return;
            }
            if (httpContext.Request.Cookies.ContainsKey(key))
            {
                httpContext.Response.Cookies.Delete(key);
            }

            value = Utilities.EncryptText(value);
            if (options == null)
            {
                httpContext.Response.Cookies.Append(key, value);
            }
            else
            {
                httpContext.Response.Cookies.Append(key, value, options);
            }
        }
 public void Delete(string key, CookieOptions options)
 {
     context.Response.Cookies.Delete(key, options);
     dic.Remove(key);
 }
Ejemplo n.º 42
0
        public static async Task SetResponse(HttpContext context, RenderContext renderContext)
        {
            var response = renderContext.Response;

            var header = context.Features.Response.Headers as Kooboo.HttpServer.Http.HttpResponseHeaders;

            context.Features.Response.StatusCode = response.StatusCode;

            if (response.StatusCode == 200)
            {
                context.Features.Response.Headers["Server"] = "http://www.kooboo.com";

                foreach (var item in response.Headers)
                {
                    context.Features.Response.Headers[item.Key] = item.Value;
                }

                foreach (var item in response.DeletedCookieNames)
                {
                    // context.Features.Response.Cookies.Delete(item);
                    var options = new CookieOptions()
                    {
                        Domain  = renderContext.Request.Host,
                        Path    = "/",
                        Expires = DateTime.Now.AddDays(-30)
                    };
                    context.Features.Response.Cookies.Append(item, "", options);

                    response.AppendedCookies.RemoveAll(o => o.Name == item);
                }

                foreach (var item in response.AppendedCookies)
                {
                    if (string.IsNullOrEmpty(item.Domain))
                    {
                        item.Domain = renderContext.Request.Host;
                    }
                    if (string.IsNullOrEmpty(item.Path))
                    {
                        item.Path = "/";
                    }

                    //if (item.Expires == default(DateTime))
                    //{
                    //    context.Features.Response.Cookies.Append(item.Name, item.Value);
                    //}
                    //else
                    //{

                    if (item.Expires == default(DateTime))
                    {
                        var time = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local);
                        time         = time.AddSeconds(-1);
                        item.Expires = time;
                    }

                    var options = new CookieOptions()
                    {
                        Domain  = item.Domain,
                        Path    = item.Path,
                        Expires = item.Expires
                    };

                    context.Features.Response.Cookies.Append(item.Name, item.Value, options);
                    // }
                }

                header.HeaderContentType = response.ContentType;

                if (response.Body != null && context.Features.Request.Method.ToLower() != "head")
                {
                    //int len = response.Body.Length;
                    //if (len > 0)
                    //{
                    try
                    {
                        header.ContentLength = response.Body.Length;
                        await context.Features.Response.Body.WriteAsync(response.Body, 0, response.Body.Length).ConfigureAwait(false);
                    }
                    catch (Exception)
                    {
                        context.Features.Response.Body.Close();
                    }
                    //}
                }
                else
                {
                    if (response.Stream != null)
                    {
                        response.Stream.CopyTo(context.Features.Response.Body);
                    }

                    else
                    {
                        // 404.
                        string filename = Lib.Helper.IOHelper.CombinePath(AppSettings.RootPath, Kooboo.DataConstants.Default404Page) + ".html";
                        if (System.IO.File.Exists(filename))
                        {
                            string text  = System.IO.File.ReadAllText(filename);
                            var    bytes = System.Text.Encoding.UTF8.GetBytes(text);
                            header.ContentLength = bytes.Length;
                            context.Features.Response.StatusCode = 404;
                            await context.Features.Response.Body.WriteAsync(bytes, 0, bytes.Length);
                        }
                    }
                }
            }
            else
            {
                string location = response.RedirectLocation;

                foreach (var item in response.DeletedCookieNames)
                {
                    var options = new CookieOptions()
                    {
                        Domain  = renderContext.Request.Host,
                        Path    = "/",
                        Expires = DateTime.Now.AddDays(-30)
                    };

                    context.Features.Response.Cookies.Append(item, "", options);
                }

                foreach (var item in response.AppendedCookies)
                {
                    if (string.IsNullOrEmpty(item.Domain))
                    {
                        item.Domain = renderContext.Request.Host;
                    }
                    if (string.IsNullOrEmpty(item.Path))
                    {
                        item.Path = "/";
                    }

                    var options = new CookieOptions()
                    {
                        Domain  = item.Domain,
                        Path    = item.Path,
                        Expires = item.Expires
                    };

                    context.Features.Response.Cookies.Append(item.Name, item.Value, options);
                }

                if (!string.IsNullOrEmpty(location))
                {
                    location = GetEncodedLocation(location);

                    var host = renderContext.Request.Port == 80 || renderContext.Request.Port == 443
                        ? renderContext.Request.Host
                        : string.Format("{0}:{1}", renderContext.Request.Host, renderContext.Request.Port);
                    string BaseUrl = renderContext.Request.Scheme + "://" + host + renderContext.Request.Path;
                    var    newUrl  = UrlHelper.Combine(BaseUrl, location);
                    if (response.StatusCode != 200)
                    {
                        context.Features.Response.StatusCode = response.StatusCode;
                    }
                    //status code doesn't start with 3xx,it'will not redirect.
                    if (!response.StatusCode.ToString().StartsWith("3"))
                    {
                        context.Features.Response.StatusCode = StatusCodes.Status302Found;
                    }

                    header.HeaderLocation = newUrl;

                    context.Features.Response.Body.Dispose();

                    Log(renderContext);
                    return;
                }

                if (response.Body != null && response.Body.Length > 0)
                {
                    context.Features.Response.StatusCode = response.StatusCode;
                    await context.Features.Response.Body.WriteAsync(response.Body, 0, response.Body.Length).ConfigureAwait(false);

                    context.Features.Response.Body.Dispose();
                    Log(renderContext);
                    return;
                }

                context.Features.Response.StatusCode = response.StatusCode;
                string responsebody = null;
                switch (response.StatusCode)
                {
                case 404:
                    responsebody = " The requested resource not found";
                    break;

                case 301:
                    responsebody = " The requested resource has moved.";
                    break;

                case 302:
                    responsebody = " The requested resource has moved.";
                    break;

                case 401:
                    responsebody = " Unauthorized access";
                    break;

                case 403:
                    responsebody = " Unauthorized access";
                    break;

                case 407:
                    responsebody = "Reach Limitation";
                    break;

                case 500:
                    responsebody = "Internal server error";
                    break;

                case 503:
                    responsebody = " Service Unavailable";
                    break;

                default:
                    break;
                }

                if (string.IsNullOrEmpty(responsebody))
                {
                    if (response.StatusCode >= 400 && response.StatusCode < 500)
                    {
                        responsebody = " Client error";
                    }
                    else if (response.StatusCode >= 500)
                    {
                        responsebody = " Server error";
                    }
                    else
                    {
                        responsebody = " Unknown error";
                    }
                }
                var bytes = Encoding.UTF8.GetBytes(responsebody);
                await context.Features.Response.Body.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
            }


            context.Features.Response.Body.Dispose();
            Log(renderContext);
            context = null;
        }
Ejemplo n.º 43
0
        public async Task Invoke(HttpContext httpContext, IOptions <JwtBearerTokenSettings> jwtTokenOptions, UserManager <User> userMgr, RefreshTokenRepository refreshTokenRepository)
        {
            string accessToken  = httpContext.Request.Cookies["accessToken"];
            string refreshToken = httpContext.Request.Cookies["refreshToken"];

            httpContext.Items["accessToken"] = httpContext.Request.Cookies["accessToken"];


            if (accessToken != null && refreshToken != null)
            {
                var tokenHandler       = new JwtSecurityTokenHandler();
                JwtSecurityToken token = tokenHandler.ReadJwtToken(accessToken);
                var expDate            = token.ValidTo;


                if (expDate < DateTime.UtcNow)
                {
                    var          nameid       = token.Claims.Where(c => c.Type == "nameid").FirstOrDefault();
                    RefreshToken refresh      = refreshTokenRepository.GetByUserIdAndToken(nameid.Value, refreshToken);
                    User         identityUser = await userMgr.FindByIdAsync(nameid.Value);

                    if (refresh != null)
                    {
                        if (refresh.ExpiryOn < DateTime.UtcNow || identityUser.IsLocked == true)
                        {
                            await refreshTokenRepository.Remove(refresh.Id);

                            // Set Token Cookie
                            var cookieOptions = new CookieOptions
                            {
                                HttpOnly = true,
                                Secure   = true,
                                SameSite = SameSiteMode.None,
                                Expires  = DateTime.UtcNow.AddDays(-1)
                            };
                            httpContext.Response.Cookies.Append("accessToken", "", cookieOptions);
                            httpContext.Response.Cookies.Append("refreshToken", "", cookieOptions);
                            httpContext.Items["accessToken"] = "";
                        }
                        else
                        {
                            var key         = Encoding.UTF8.GetBytes(jwtTokenOptions.Value.SecretKey);
                            var unique_name = token.Claims.Where(c => c.Type == "unique_name").FirstOrDefault();
                            var email       = token.Claims.Where(c => c.Type == "email").FirstOrDefault();
                            var role        = token.Claims.Where(c => c.Type == "role").FirstOrDefault();

                            var tokenDescriptor = new SecurityTokenDescriptor
                            {
                                Subject = new ClaimsIdentity(new Claim[]
                                {
                                    new Claim(ClaimTypes.NameIdentifier, nameid.Value),
                                    new Claim(ClaimTypes.Name, unique_name.Value),
                                    new Claim(ClaimTypes.Email, email.Value),
                                    new Claim(ClaimTypes.Role, role.Value)
                                }),

                                Expires            = DateTime.UtcNow.AddSeconds(jwtTokenOptions.Value.ExpiryTimeInSeconds),
                                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
                                Audience           = jwtTokenOptions.Value.Audience,
                                Issuer             = jwtTokenOptions.Value.Issuer
                            };

                            // Set Access Token Cookie
                            var accessTokenCookieOptions = new CookieOptions
                            {
                                HttpOnly = true,
                                Secure   = true,
                                SameSite = SameSiteMode.None
                                           //Expires = DateTime.UtcNow.AddDays(7)
                            };
                            httpContext.Response.Cookies.Append("accessToken", tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor)), accessTokenCookieOptions);
                            httpContext.Items["accessToken"] = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
                        }
                    }
                }
            }

            //httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
            await nextDelegate.Invoke(httpContext);
        }
        protected override Task ApplyResponseGrantAsync()
        {
            var signin  = this.Helper.LookupSignIn(this.Options.AuthenticationType);
            var signout = this.Helper.LookupSignOut(this.Options.AuthenticationType, this.Options.AuthenticationMode);

            if (signin != null)
            {
                // Save access token, refresh token and identity token as cookies
                if (this.Options.CookieConfiguration.SaveTokens)
                {
                    var accessToken   = signin.Properties.Dictionary.ContainsKey("access_token") ? signin.Properties.Dictionary["access_token"] : null;
                    var refreshToken  = signin.Properties.Dictionary.ContainsKey("refresh_token") ? signin.Properties.Dictionary["refresh_token"] : null;
                    var identityToken = signin.Properties.Dictionary.ContainsKey("id_token") ? signin.Properties.Dictionary["id_token"] : null;

                    if (!string.IsNullOrEmpty(accessToken))
                    {
                        this.Context.Response.Cookies.Append(
                            $"{this.Options.CookieConfiguration.Name}_AT",
                            accessToken,
                            new CookieOptions()
                        {
                            Domain  = this.Context.Request.Uri.Host,
                            Expires = signin.Properties.ExpiresUtc?.DateTime,
                            Secure  = this.Context.Request.IsSecure
                        });
                    }

                    if (!string.IsNullOrEmpty(refreshToken))
                    {
                        this.Context.Response.Cookies.Append(
                            $"{this.Options.CookieConfiguration.Name}_RT",
                            refreshToken,
                            new CookieOptions()
                        {
                            Domain  = this.Context.Request.Uri.Host,
                            Expires = signin.Properties.ExpiresUtc?.DateTime.Add(this.Options.RefreshTokenLifetime),
                            Secure  = this.Context.Request.IsSecure
                        });
                    }

                    if (!string.IsNullOrEmpty(identityToken))
                    {
                        this.Context.Response.Cookies.Append(
                            $"{this.Options.CookieConfiguration.Name}_IT",
                            identityToken,
                            new CookieOptions()
                        {
                            Domain  = this.Context.Request.Uri.Host,
                            Expires = signin.Properties.ExpiresUtc?.DateTime,
                            Secure  = this.Context.Request.IsSecure
                        });
                    }
                }
            }
            else if (signout != null)
            {
                var opts = new CookieOptions()
                {
                    Domain = this.Request.Uri.Host, Secure = this.Request.IsSecure
                };

                // Remove cookies from response
                this.Context.Response.Cookies.Delete($"{this.Options.CookieConfiguration.Name}_AT", opts);
                this.Context.Response.Cookies.Delete($"{this.Options.CookieConfiguration.Name}_RT", opts);
                this.Context.Response.Cookies.Delete($"{this.Options.CookieConfiguration.Name}_IT", opts);

                // Set authentication properties to prevent further processing
                this.Context.Authentication.User = new GenericPrincipal(new GenericIdentity("signout"), new [] { "urn:oauth:noauth" });

                return(Task.FromResult <object>(null));
            }

            return(base.ApplyResponseGrantAsync());
        }
Ejemplo n.º 45
0
 public void Delete(string key, CookieOptions options)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 46
0
        public IActionResult OnPost()
        {
            //检验用户名和密码是否符合规范
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            DBUser = DBContext.Users.Where(a => a.Name == User.Name).FirstOrDefault();

            //验证 用户名/密码/验证码 是否正确
            if (DBUser is null)
            {
                ViewData["result"] = "该用户不存在";
                return(Page());
            }
            else
            {
                if (User.password != DBUser.password)
                {
                    ViewData["result"] = "密码错误";
                    return(Page());
                }
                else
                {
                    if (Captcha != HttpContext.Session.GetString("captcha"))
                    {
                        ViewData["result"] = "验证码错误";
                        return(Page());
                    }
                    else
                    {
                        ViewData["result"] = "登录成功";

                        CookieOptions Options;
                        if (RememberMe)
                        {
                            Options = new CookieOptions()
                            {
                                Expires = DateTime.Now.AddDays(14)
                            };
                            //登录页面刚刚加载完成的时候不可以清理缓存,否则页面报错
                        }
                        else
                        {
                            Options = new CookieOptions()
                            {
                                Expires = DateTime.Now.AddDays(1)
                            };
                        }
                        Response.Cookies.Append("User.Name", DBUser.Name.ToString(), Options);

                        bool result = Request.Query.TryGetValue("parameter", out StringValues parameter);
                        if (result)
                        {
                            return(RedirectToPage(parameter));
                        }
                        else
                        {
                            return(Page());
                        }
                    }
                }
            }
        }
        public static void PersistAccessibleResources(this Controller controller,
                                                      ICollection <string> resources, IDataProtector dataProtector, CookieOptions cookieOptions = null)
        {
            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }

            if (resources == null)
            {
                throw new ArgumentNullException(nameof(resources));
            }

            if (dataProtector == null)
            {
                throw new ArgumentNullException(nameof(dataProtector));
            }

            var now     = DateTime.UtcNow;
            var expires = now.AddSeconds(3600);

            cookieOptions = cookieOptions == null ? new CookieOptions
            {
                Expires = expires
            } : cookieOptions;
            var json    = JsonConvert.SerializeObject(resources);
            var protect = dataProtector.Protect(json);

            controller.Response.Cookies.Append(Constants.DefaultCookieName, protect, cookieOptions);
        }
Ejemplo n.º 48
0
        /// <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(IOwinContext context, string key, string value, CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
            bool pathHasValue = !string.IsNullOrEmpty(options.Path);
            bool expiresHasValue = options.Expires.HasValue;

            string escapedKey = Uri.EscapeDataString(key);
            string prefix = escapedKey + "=";

            string suffix = string.Concat(
                !domainHasValue ? null : "; domain=",
                !domainHasValue ? null : options.Domain,
                !pathHasValue ? null : "; path=",
                !pathHasValue ? null : options.Path,
                !expiresHasValue ? null : "; expires=",
                !expiresHasValue ? null : options.Expires.Value.ToString("ddd, dd-MMM-yyyy HH:mm:ss ", CultureInfo.InvariantCulture) + "GMT",
                !options.Secure ? null : "; secure",
                !options.HttpOnly ? null : "; HttpOnly");

            value = value ?? string.Empty;
            bool quoted = false;
            if (IsQuoted(value))
            {
                quoted = true;
                value = RemoveQuotes(value);
            }
            string escapedValue = Uri.EscapeDataString(value);

            // Normal cookie
            IHeaderDictionary responseHeaders = context.Response.Headers;
            if (!ChunkSize.HasValue || ChunkSize.Value > prefix.Length + escapedValue.Length + suffix.Length + (quoted ? 2 : 0))
            {
                string setCookieValue = string.Concat(
                    prefix,
                    quoted ? Quote(escapedValue) : escapedValue,
                    suffix);
                responseHeaders.AppendValues(Constants.Headers.SetCookie, setCookieValue);
            }
            else if (ChunkSize.Value < prefix.Length + suffix.Length + (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=/
                int dataSizePerCookie = ChunkSize.Value - prefix.Length - suffix.Length - (quoted ? 2 : 0) - 3; // Budget 3 chars for the chunkid.
                int cookieChunkCount = (int)Math.Ceiling(escapedValue.Length * 1.0 / dataSizePerCookie);

                responseHeaders.AppendValues(Constants.Headers.SetCookie, prefix + "chunks:" + cookieChunkCount.ToString(CultureInfo.InvariantCulture) + suffix);
                
                string[] chunks = new string[cookieChunkCount];
                int offset = 0;
                for (int chunkId = 1; chunkId <= cookieChunkCount; chunkId++)
                {
                    int remainingLength = escapedValue.Length - offset;
                    int length = Math.Min(dataSizePerCookie, remainingLength);
                    string segment = escapedValue.Substring(offset, length);
                    offset += length;

                    chunks[chunkId - 1] = string.Concat(
                                            escapedKey,
                                            "C",
                                            chunkId.ToString(CultureInfo.InvariantCulture),
                                            "=",
                                            quoted ? "\"" : string.Empty,
                                            segment,
                                            quoted ? "\"" : string.Empty,
                                            suffix);
                }
                responseHeaders.AppendValues(Constants.Headers.SetCookie, chunks);
            }
        }