コード例 #1
0
        /// <summary>
        /// Invokes the logic of the middleware.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/>.</param>
        /// <returns>A <see cref="Task"/> that completes when the middleware has completed processing.</returns>
        public async Task Invoke(HttpContext context)
        {
            var         isNewSessionKey     = false;
            Func <bool> tryEstablishSession = ReturnTrue;
            var         cookieValue         = context.Request.Cookies[_options.Cookie.Name];
            var         sessionKey          = CookieProtection.Unprotect(_dataProtector, cookieValue, _logger);

            if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
            {
                // No valid cookie, new session.
                var guidBytes = new byte[16];
                RandomNumberGenerator.Fill(guidBytes);
                sessionKey  = new Guid(guidBytes).ToString();
                cookieValue = CookieProtection.Protect(_dataProtector, sessionKey);
                var establisher = new SessionEstablisher(context, cookieValue, _options);
                tryEstablishSession = establisher.TryEstablishSession;
                isNewSessionKey     = true;
            }

            var feature = new SessionFeature();

            feature.Session = _sessionStore.Create(sessionKey, _options.IdleTimeout, _options.IOTimeout, tryEstablishSession, isNewSessionKey);
            context.Features.Set <ISessionFeature>(feature);

            try
            {
                await _next(context);
            }
            finally
            {
                context.Features.Set <ISessionFeature>(null);

                if (feature.Session != null)
                {
                    try
                    {
                        await feature.Session.CommitAsync();
                    }
                    catch (OperationCanceledException)
                    {
                        _logger.SessionCommitCanceled();
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorClosingTheSession(ex);
                    }
                }
            }
        }
コード例 #2
0
        /// <summary>
        /// Invokes the logic of the middleware.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/>.</param>
        /// <returns>A <see cref="Task"/> that completes when the middleware has completed processing.</returns>
        public async Task Invoke(HttpContext context)
        {
            var         isNewSessionKey     = false;
            Func <bool> tryEstablishSession = ReturnTrue;
            //var cookieValue = context.Request.Cookies[_options.Cookie.Name]; //old code
            //var sessionKey = CookieProtection.Unprotect(_dataProtector, cookieValue, _logger); //old code
            var sessionInfo = this.getSessionKeyInfo(context);
            var sessionKey  = sessionInfo.Item1;

            if (sessionInfo.Item2)                                                       //string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
            {
                var establisher = new SessionEstablisher(context, sessionKey, _options); // cookieValue, _options);
                tryEstablishSession = establisher.TryEstablishSession;
                isNewSessionKey     = true;
            }

            var feature = new SessionFeature();

            feature.Session = _sessionStore.Create(sessionKey, _options.IdleTimeout, _options.IOTimeout, tryEstablishSession, isNewSessionKey);
            context.Features.Set <ISessionFeature>(feature);

            try
            {
                await _next(context);
            }
            finally
            {
                context.Features.Set <ISessionFeature>(null);

                if (feature.Session != null)
                {
                    try
                    {
                        await feature.Session.CommitAsync(context.RequestAborted);
                    }
                    catch (OperationCanceledException)
                    {
                        _logger.SessionCommitCanceled();
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorClosingTheSession(ex);
                    }
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// Invokes the logic of the middleware.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/>.</param>
        /// <returns>A <see cref="Task"/> that completes when the middleware has completed processing.</returns>
        public async Task Invoke(HttpContext context)
        {
            var         isNewSessionKey     = false;
            Func <bool> tryEstablishSession = ReturnTrue;
            var         cookieValue         = context.Request.Headers[_options.Cookie.Name];
            var         sessionKey          = CookieProtection.Unprotect(_dataProtector, cookieValue, _logger);

            if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
            {
                // No valid cookie, new session.
                var guidBytes = new byte[16];
                CryptoRandom.GetBytes(guidBytes);
                sessionKey  = new Guid(guidBytes).ToString();
                cookieValue = CookieProtection.Protect(_dataProtector, sessionKey);
                var establisher = new SessionEstablisher(context, cookieValue, _options);
                tryEstablishSession = establisher.TryEstablishSession;
                isNewSessionKey     = true;
            }

            var feature = new SessionFeature();

            feature.Session = _sessionStore.Create(sessionKey, TimeSpan.FromMinutes(120.0), TimeSpan.FromMinutes(3.0), tryEstablishSession, isNewSessionKey);
            context.Features.Set <ISessionFeature>(feature);

            try
            {
                await _next(context);
            }
            finally
            {
                context.Features.Set <ISessionFeature>(null);

                if (feature.Session != null)
                {
                    try
                    {
                        await feature.Session.CommitAsync(context.RequestAborted);
                    }
                    catch (OperationCanceledException ex)
                    {
                        _logger.LogError(ex.Message);
                    }
                }
            }
        }
コード例 #4
0
        public async Task Invoke(HttpContext context)
        {
            var         isNewSessionKey     = false;
            Func <bool> tryEstablishSession = ReturnTrue;
            var         sessionKey          = context.Request.Cookies.Get(_options.CookieName);

            if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
            {
                // No valid cookie, new session.
                var guidBytes = new byte[16];
                CryptoRandom.GetBytes(guidBytes);
                sessionKey = new Guid(guidBytes).ToString();
                var establisher = new SessionEstablisher(context, sessionKey, _options);
                tryEstablishSession = establisher.TryEstablishSession;
                isNewSessionKey     = true;
            }

            var feature = new SessionFeature();

            feature.Factory = new SessionFactory(sessionKey, _options.Store, _options.IdleTimeout, tryEstablishSession, isNewSessionKey);
            feature.Session = feature.Factory.Create();
            context.SetFeature <ISessionFeature>(feature);

            try
            {
                await _next(context);
            }
            finally
            {
                context.SetFeature <ISessionFeature>(null);

                if (feature.Session != null)
                {
                    try
                    {
                        feature.Session.Commit();
                    }
                    catch (Exception ex)
                    {
                        _logger.WriteError("Error closing the session.", ex);
                    }
                }
            }
        }
コード例 #5
0
        public async Task Invoke(HttpContext context)
        {
            var isNewSessionKey = false;
            Func<bool> tryEstablishSession = ReturnTrue;
            var sessionKey = context.Request.Cookies.Get(_options.CookieName);
            if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
            {
                // No valid cookie, new session.
                var guidBytes = new byte[16];
                CryptoRandom.GetBytes(guidBytes);
                sessionKey = new Guid(guidBytes).ToString();
                var establisher = new SessionEstablisher(context, sessionKey, _options);
                tryEstablishSession = establisher.TryEstablishSession;
                isNewSessionKey = true;
            }

            var feature = new SessionFeature();
            feature.Factory = new SessionFactory(sessionKey, _options.Store, _options.IdleTimeout, tryEstablishSession, isNewSessionKey);
            feature.Session = feature.Factory.Create();
            context.SetFeature<ISessionFeature>(feature);

            try
            {
                await _next(context);
            }
            finally
            {
                context.SetFeature<ISessionFeature>(null);

                if (feature.Session != null)
                {
                    try
                    {
                        feature.Session.Commit();
                    }
                    catch (Exception ex)
                    {
                        _logger.WriteError("Error closing the session.", ex);
                    }
                }
            }
        }
コード例 #6
0
        public async Task Invoke(HttpContext context)
        {
            var         isNewSessionKey     = false;
            Func <bool> tryEstablishSession = ReturnTrue;
            var         headerName          = DotNet.Configuration.Config.GetSection("Session:HeaderName").Value ?? _options.Cookie.Name;
            var         cookieValue         = context.Request.Headers[headerName].ToString();

            if (string.IsNullOrWhiteSpace(cookieValue))
            {
                cookieValue = context.Request.Cookies[_options.Cookie.Name];
            }
            var sessionKey = cookieValue;

            if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
            {
                // No valid cookie, new session.
                var guidBytes = new byte[16];
                CryptoRandom.GetBytes(guidBytes);
                cookieValue = $"{new Guid(guidBytes):n}{Guid.NewGuid():n}";
                sessionKey  = cookieValue.ToMD5();
                var establisher = new SessionEstablisher(context, cookieValue, _options);
                tryEstablishSession = establisher.TryEstablishSession;
                isNewSessionKey     = true;
            }
            else
            {
                sessionKey = cookieValue.ToMD5();
            }

            var feature = new SessionFeature
            {
                Session = _sessionStore.Create(sessionKey, _options.IdleTimeout, _options.IOTimeout, tryEstablishSession, isNewSessionKey)
            };

            feature.Session.SetString("SessionKey", cookieValue);
            context.Features.Set <ISessionFeature>(feature);
            try
            {
                await _next(context);
            }
            finally
            {
                context.Features.Set <ISessionFeature>(null);

                if (feature.Session != null)
                {
                    try
                    {
                        await feature.Session.CommitAsync(context.RequestAborted);
                    }
                    catch (OperationCanceledException)
                    {
                        // _logger.SessionCommitCanceled();
                    }
                    catch (Exception)
                    {
                        //_logger.ErrorClosingTheSession(ex);
                    }
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// Invokes the logic of the middleware.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/>.</param>
        /// <returns>A <see cref="Task"/> that completes when the middleware has completed processing.</returns>
        public async Task Invoke(HttpContext context)
        {
            var         isNewSessionKey     = false;
            Func <bool> tryEstablishSession = ReturnTrue;
            var         cookieValue         = context.Request.Cookies[_options.Cookie.Name];
            var         sessionKey          = CookieProtection.Unprotect(_dataProtector, cookieValue, _logger);

            if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
            {
                // No valid cookie, new session.
                var guidBytes = new byte[16];
                RandomNumberGenerator.Fill(guidBytes);
                sessionKey  = new Guid(guidBytes).ToString();
                cookieValue = CookieProtection.Protect(_dataProtector, sessionKey);
                var establisher = new SessionEstablisher(context, cookieValue, _options);
                tryEstablishSession = establisher.TryEstablishSession;
                isNewSessionKey     = true;
            }

            var feature = new SessionFeature
            {
                Session = _sessionStore.Create(sessionKey, _options.IdleTimeout, _options.IOTimeout, tryEstablishSession, isNewSessionKey)
            };

            var isSessionStart   = context.Request.Path.Value == "/api/authorization/logon";
            var isSessionStartAs = context.Request.Path.Value == "/api/authorization/logonas";
            var isSessionCheck   = context.Request.Path.Value == "/api/session";

            context.Features.Set <ISessionFeature>(feature);

            if (!isSessionStart && !isSessionStartAs && !isSessionCheck)
            {
                var result = await _sessionService.ValidateSession(sessionKey).ConfigureAwait(false);

                if (result == false)
                {
                    context.Response.StatusCode = StatusCodes.Status403Forbidden;
                    await context.Response.WriteAsync("Session expired!");

                    return;
                }
            }

            try
            {
                await _next(context);
            }
            finally
            {
                context.Features.Set <ISessionFeature>(null);

                if (feature.Session != null)
                {
                    try
                    {
                        await feature.Session.CommitAsync();
                    }
                    catch (OperationCanceledException)
                    {
                        _logger.SessionCommitCanceled();
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorClosingTheSession(ex);
                    }
                }
            }
        }