public IActionResult Login(LoginModel model)
        {
            var vm = new LoginViewModel();
            vm.Model = model;

            if (!ModelState.IsValid)
            {
                vm.Result = OperationResult.ErrorResult("错误的请求");
                return this.View(vm);
            }

            var result = this.AuthService.Login(model.UserName, model.Password);
            if (result.Success)
            {
                var option = new CookieOptions();
                if (model.RememberMe)
                {
                    option.Expires = DateTime.Now.AddMonths(6);
                }

                this.Response.Cookies.Append("token", result.Data, option);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                vm.Result = result;
                return this.View(vm);
            }            
        }
 public AppendCookieContext(HttpContext context, CookieOptions options, string name, string value)
 {
     Context = context;
     CookieOptions = options;
     CookieName = name;
     CookieValue = value;
 }
        private CookieOptions CreateCookieOptions(bool? persistent, DateTimeOffset? expires = null)
        {
            var secure = _context.HttpContext.Request.IsHttps;
            var path = _context.GetBasePath().CleanUrlPath();

            var options = new CookieOptions
            {
                HttpOnly = false,
                Secure = secure,
                Path = path
            };

            // todo: load authN cookie and copy its values for persistent/expiration
            //if (persistent != false)
            //{
            //    if (persistent == true || _context.Options.AuthenticationOptions.CookieAuthenticationOptions.IsPersistent)
            //    {
            //        if (persistent == true)
            //        {
            //            expires = expires ?? DateTimeHelper.UtcNow.Add(this.identityServerOptions.AuthenticationOptions.CookieOptions.RememberMeDuration);
            //        }
            //        else
            //        {
            //            expires = expires ?? DateTimeHelper.UtcNow.Add(this.identityServerOptions.AuthenticationOptions.CookieOptions.ExpireTimeSpan);
            //        }
            //        options.Expires = expires.Value.UtcDateTime;
            //    }
            //}

            return options;
        }
Example #4
0
        void SetCookie(string value)
        {
            DateTime? expires = null;
            if (String.IsNullOrWhiteSpace(value))
            {
                var existingValue = GetCookie();
                if (existingValue == null)
                {
                    // no need to write cookie to clear if we don't already have one
                    return;
                }

                value = ".";
                expires = DateTime.Now.AddYears(-1);
            }

            var opts = new CookieOptions
            {
                HttpOnly = true,
                Secure = false,
                Path = "/",
                Expires = expires
            };

            Response.Cookies.Append(CookieName, value, opts);
        }
        public static string Login(HttpContext context, Guid userId, DateTime? modifiedOn, bool rememberMe, IErpService service)
        {
            var identity = CreateIdentity(userId, service);

            if (identity == null)
                throw new Exception("Try to login with invalid user.");

            if (modifiedOn != identity.User.ModifiedOn)
                modifiedOn = identity.User.ModifiedOn;



            ErpUser user = new SecurityManager(service).GetUser(userId);
            string token = AuthToken.Create(user, rememberMe).Encrypt();
            if (rememberMe)
            {
                CookieOptions options = new CookieOptions();
                options.Expires = DateTime.Today.AddDays(AUTH_REMEMBER_IDENTITY_DAYS);
                context.Response.Cookies.Append(AUTH_TOKEN_KEY, token, options);
            }
            else
                context.Response.Cookies.Append(AUTH_TOKEN_KEY, token);

            context.User = new ErpPrincipal(identity);

            new SecurityManager(service).UpdateUserLastLoginTime(userId);

            return token;
        }
        public HttpStatusCodeResult SignOut()
        {
            if (Request.Cookies.ContainsKey("user"))
            {
                var options = new CookieOptions();
                options.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Append("user", "", options);
              //  HttpContext.Response.Cookies.Delete("user");
            }

            return new HttpOkResult();
        }
 /// <summary>
 /// Creates a new instance of the context object.
 /// </summary>
 /// <param name="context">The HTTP request context</param>
 /// <param name="options">The middleware options</param>
 /// <param name="authenticationScheme">Initializes AuthenticationScheme property</param>
 /// <param name="principal">Initializes Principal property</param>
 /// <param name="properties">Initializes Extra property</param>
 /// <param name="cookieOptions">Initializes options for the authentication cookie.</param>
 public CookieSigningInContext(
     HttpContext context,
     CookieAuthenticationOptions options,
     string authenticationScheme,
     ClaimsPrincipal principal,
     AuthenticationProperties properties,
     CookieOptions cookieOptions)
     : base(context, options)
 {
     AuthenticationScheme = authenticationScheme;
     Principal = principal;
     Properties = properties;
     CookieOptions = cookieOptions;
 }
Example #8
0
        public void SaveCookieToken(HttpContext httpContext, AntiForgeryToken token)
        {
            var serializedToken = _serializer.Serialize(token);
            var options = new CookieOptions() { HttpOnly = true };

            // Note: don't use "newCookie.Secure = _config.RequireSSL;" since the default
            // value of newCookie.Secure is poulated out of band.
            if (_config.RequireSSL)
            {
                options.Secure = true;
            }

            httpContext.Response.Cookies.Append(_config.CookieName, serializedToken, options);
        }
Example #9
0
        public void SaveCookieToken(HttpContext httpContext, AntiForgeryToken token)
        {
            // Add the cookie to the request based context.
            // This is useful if the cookie needs to be reloaded in the context of the same request.
            var contextAccessor =
                httpContext.RequestServices.GetRequiredService<IScopedInstance<AntiForgeryContext>>();
            Debug.Assert(contextAccessor.Value == null, "AntiForgeryContext should be set only once per request.");
            contextAccessor.Value = new AntiForgeryContext() { CookieToken = token };

            var serializedToken = _serializer.Serialize(token);
            var options = new CookieOptions() { HttpOnly = true };

            // Note: don't use "newCookie.Secure = _config.RequireSSL;" since the default
            // value of newCookie.Secure is poulated out of band.
            if (_config.RequireSSL)
            {
                options.Secure = true;
            }

            httpContext.Response.Cookies.Append(_config.CookieName, serializedToken, options);
        }
        public void SaveCookieToken(HttpContext httpContext, AntiforgeryToken token)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

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

            // Add the cookie to the request based context.
            // This is useful if the cookie needs to be reloaded in the context of the same request.

            var services = httpContext.RequestServices;
            var contextAccessor = services.GetRequiredService<IAntiforgeryContextAccessor>();
            Debug.Assert(contextAccessor.Value == null, "AntiforgeryContext should be set only once per request.");
            contextAccessor.Value = new AntiforgeryContext() { CookieToken = token };

            var serializedToken = _tokenSerializer.Serialize(token);
            var options = new CookieOptions() { HttpOnly = true };

            // Note: don't use "newCookie.Secure = _options.RequireSSL;" since the default
            // value of newCookie.Secure is poulated out of band.
            if (_options.RequireSsl)
            {
                options.Secure = true;
            }

            httpContext.Response.Cookies.Append(_options.CookieName, serializedToken, options);
        }
            private void SetCookie()
            {
                var cookieOptions = new CookieOptions
                {
                    Domain = _options.CookieDomain,
                    HttpOnly = _options.CookieHttpOnly,
                    Path = _options.CookiePath ?? "/",
                };

                _context.Response.Cookies.Append(_options.CookieName, _sessionKey, cookieOptions);

                _context.Response.Headers.Set(
                    "Cache-Control",
                    "no-cache");

                _context.Response.Headers.Set(
                    "Pragma",
                    "no-cache");

                _context.Response.Headers.Set(
                    "Expires",
                    "-1");
            }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="context"></param>
 /// <param name="options"></param>
 /// <param name="cookieOptions"></param>
 public CookieSigningOutContext(HttpContext context, CookieAuthenticationOptions options, CookieOptions cookieOptions)
     : base(context, options)
 {
     CookieOptions = cookieOptions;
 }
 public void Delete(string key, CookieOptions options)
 {
     throw new NotImplementedException();
 }
 public void Append(string key, string value, CookieOptions options)
 {
     this.Key = key;
     this.Value = value;
     this.Options = options;
     this.Count++;
 }
        /// <summary>
        /// Appends a new response cookie to the Set-Cookie header. If the cookie is larger than the given size limit
        /// then it will be broken down into multiple cookies as follows:
        /// Set-Cookie: CookieName=chunks:3; path=/
        /// Set-Cookie: CookieNameC1=Segment1; path=/
        /// Set-Cookie: CookieNameC2=Segment2; path=/
        /// Set-Cookie: CookieNameC3=Segment3; path=/
        /// </summary>
        /// <param name="context"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="options"></param>
        public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

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

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

            var escapedKey = Encoder.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.Append(Constants.Headers.SetCookie, template.ToString());
            }
            else if (ChunkSize.Value < templateLength + (quoted ? 2 : 0) + 10)
            {
                // 10 is the minimum data we want to put in an individual cookie, including the cookie chunk identifier "CXX".
                // No room for data, we can't chunk the options and name
                throw new InvalidOperationException(Resources.Exception_CookieLimitTooSmall);
            }
            else
            {
                // Break the cookie down into multiple cookies.
                // Key = CookieName, value = "Segment1Segment2Segment2"
                // Set-Cookie: CookieName=chunks:3; path=/
                // Set-Cookie: CookieNameC1="Segment1"; path=/
                // Set-Cookie: CookieNameC2="Segment2"; path=/
                // Set-Cookie: CookieNameC3="Segment3"; path=/
                var dataSizePerCookie = ChunkSize.Value - templateLength - (quoted ? 2 : 0) - 3; // Budget 3 chars for the chunkid.
                var cookieChunkCount = (int)Math.Ceiling(escapedValue.Length * 1.0 / dataSizePerCookie);

                template.Value = "chunks:" + cookieChunkCount.ToString(CultureInfo.InvariantCulture);
                responseHeaders.Append(Constants.Headers.SetCookie, template.ToString());

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

                    template.Name = escapedKey + "C" + chunkId.ToString(CultureInfo.InvariantCulture);
                    template.Value = quoted ? Quote(segment) : segment;
                    chunks[chunkId - 1] = template.ToString();
                }
                responseHeaders.Append(Constants.Headers.SetCookie, chunks);
            }
        }
 private void ApplyPolicy(CookieOptions options)
 {
     switch (Policy.Secure)
     {
         case SecurePolicy.Always:
             options.Secure = true;
             break;
         case SecurePolicy.SameAsRequest:
             options.Secure = Context.Request.IsHttps;
             break;
         case SecurePolicy.None:
             break;
         default:
             throw new InvalidOperationException();
     }
     switch (Policy.HttpOnly)
     {
         case HttpOnlyPolicy.Always:
             options.HttpOnly = true;
             break;
         case HttpOnlyPolicy.None:
             break;
         default:
             throw new InvalidOperationException();
     }
 }
Example #17
0
            private void SetCookie()
            {
                var cookieOptions = new CookieOptions
                {
                    Domain = _options.CookieDomain,
                    HttpOnly = _options.CookieHttpOnly,
                    Path = _options.CookiePath ?? SessionDefaults.CookiePath,
                };

                _context.Response.Cookies.Append(_options.CookieName, _sessionKey, cookieOptions);

                _context.Response.Headers["Cache-Control"] = "no-cache";
                _context.Response.Headers["Pragma"] = "no-cache";
                _context.Response.Headers["Expires"] = "-1";
            }
        protected bool ValidateCorrelationId([NotNull] AuthenticationProperties properties, [NotNull] ILogger logger)
        {
            var correlationKey = Constants.CorrelationPrefix + BaseOptions.AuthenticationScheme;
            var correlationCookie = Request.Cookies[correlationKey];
            if (string.IsNullOrWhiteSpace(correlationCookie))
            {
                logger.LogWarning("{0} cookie not found.", correlationKey);
                return false;
            }

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure = Request.IsHttps
            };
            Response.Cookies.Delete(correlationKey, cookieOptions);

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

            properties.Dictionary.Remove(correlationKey);

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

            return true;
        }
        protected void GenerateCorrelationId([NotNull] AuthenticationProperties properties)
        {
            var correlationKey = Constants.CorrelationPrefix + BaseOptions.AuthenticationScheme;

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

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

            properties.Dictionary[correlationKey] = correlationId;

            Response.Cookies.Append(correlationKey, correlationId, cookieOptions);
        }
Example #20
0
 public void Append(string key, string value, CookieOptions options)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Deletes the cookie with the given key by setting an expired state. If a matching chunked cookie exists on
        /// the request, delete each chunk.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="key"></param>
        /// <param name="options"></param>
        public void DeleteCookie(HttpContext context, string key, CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

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

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

            var 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[Constants.Headers.SetCookie];
            if (!StringValues.IsNullOrEmpty(existingValues))
            {
                responseHeaders[Constants.Headers.SetCookie] = existingValues.Where(value => !rejectPredicate(value)).ToArray();
            }

            AppendResponseCookie(
                context,
                key,
                string.Empty,
                new CookieOptions()
                {
                    Path = options.Path,
                    Domain = options.Domain,
                    Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
                });

            for (int i = 1; i <= chunks; i++)
            {
                AppendResponseCookie(
                    context,
                    key + "C" + i.ToString(CultureInfo.InvariantCulture),
                    string.Empty,
                    new CookieOptions()
                    {
                        Path = options.Path,
                        Domain = options.Domain,
                        Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
                    });
            }
        }
        private static void GenerateCorrelationId(HttpContext context, OpenIdConnectOptions options, AuthenticationProperties properties)
        {
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            var correlationKey = OpenIdConnectDefaults.CookieStatePrefix;

            var nonceBytes = new byte[32];
            CryptoRandom.GetBytes(nonceBytes);
            var correlationId = Base64UrlTextEncoder.Encode(nonceBytes);

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure = context.Request.IsHttps,
                Expires = DateTime.UtcNow + options.ProtocolValidator.NonceLifetime
            };

            properties.Items[correlationKey] = correlationId;

            context.Response.Cookies.Append(correlationKey + correlationId, NonceProperty, cookieOptions);
        }
 public DeleteCookieContext(HttpContext context, CookieOptions options, string name)
 {
     Context = context;
     CookieOptions = options;
     CookieName = name;
 }
            public void Delete(string key, CookieOptions options)
            {
                if (options == null)
                {
                    throw new ArgumentNullException(nameof(options));
                }

                ApplyPolicy(options);
                if (Policy.OnDeleteCookie != null)
                {
                    var context = new DeleteCookieContext(Context, options, key);
                    Policy.OnDeleteCookie(context);
                    key = context.CookieName;
                }
                Cookies.Delete(key, options);
            }
        protected override void SaveSharePointContext(SharePointContext spContext, HttpContext httpContext)
        {
            SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;

            //creates a cookie to store the SPCacheKey
            if (spAcsContext != null)
            {
                var options = new CookieOptions() { HttpOnly = true, Secure = true };
                httpContext.Response.Cookies.Append(SPCacheKeyKey, spAcsContext.CacheKey, options);
            }
            string output = JsonConvert.SerializeObject(spAcsContext);
            byte[] bytes = new byte[output.Length * sizeof(char)];
            System.Buffer.BlockCopy(output.ToCharArray(), 0, bytes, 0, bytes.Length);
            httpContext.Session.Set(SPContextKey, bytes);
        }
            public void Append(string key, string value, CookieOptions options)
            {
                if (options == null)
                {
                    throw new ArgumentNullException(nameof(options));
                }

                ApplyPolicy(options);
                if (Policy.OnAppendCookie != null)
                {
                    var context = new AppendCookieContext(Context, options, key, value);
                    Policy.OnAppendCookie(context);
                    key = context.CookieName;
                    value = context.CookieValue;
                }
                Cookies.Append(key, value, options);
            }
        public void Login(HttpContext context, Guid userId, DateTime? modifiedOn, bool rememberMe, IErpService service)
        {
            var identity = CreateIdentity(userId, service);

            if (identity == null)
                throw new Exception("Try to login with invalid user.");

            if (modifiedOn != identity.User.ModifiedOn)
                modifiedOn = identity.User.ModifiedOn;

            string token = AuthToken.Create(userId, modifiedOn, rememberMe).Encrypt();
            if (rememberMe)
            {
                CookieOptions options = new CookieOptions();
                options.Expires = DateTime.Today.AddDays(AUTH_REMEMBER_IDENTITY_DAYS);
                context.Response.Cookies.Append(AUTH_TOKEN_KEY, token, options);
            }
            else
                context.Response.Cookies.Append(AUTH_TOKEN_KEY, token);

            context.User = new ErpPrincipal(identity);

            //TODO
            //var dataGateway = new DataGateway(service);
            //dataGateway.UpdateUserLastLoginTime(userId);
            //dataGateway.CreateLoginLog(identity.User, identity.Customer);
        }