示例#1
0
        public void Can_retrieve_IAuthSession_with_global_ExcludeTypeInfo_set()
        {
            JsConfig.ExcludeTypeInfo = true;

            IAuthSession session = new CustomAuthSession
            {
                Id         = "sess-1",
                UserAuthId = "1",
                Custom     = "custom"
            };

            var sessionKey = SessionFeature.GetSessionKey(session.Id);

            Cache.Set(sessionKey, session, SessionFeature.DefaultSessionExpiry);

            var sessionCache = Cache.Get <IAuthSession>(sessionKey);

            Assert.That(sessionCache, Is.Not.Null);

            var typedSession = sessionCache as CustomAuthSession;

            Assert.That(typedSession, Is.Not.Null);
            Assert.That(typedSession.Custom, Is.EqualTo("custom"));

            JsConfig.Reset();
        }
示例#2
0
        public static void Init(IAppHost appHost, Func <IAuthSession> sessionFactory, params IAuthProvider[] authProviders)
        {
            if (authProviders.Length == 0)
            {
                throw new ArgumentNullException("authProviders");
            }

            DefaultOAuthProvider = authProviders[0].Provider;
            DefaultOAuthRealm    = authProviders[0].AuthRealm;

            AuthProviders = authProviders;
            if (sessionFactory != null)
            {
                CurrentSessionFactory = sessionFactory;
            }

            var test = appHost != null;

            if (test)
            {
                appHost.RegisterService <AuthService>();
                appHost.RegisterService <AssignRolesService>();
                appHost.RegisterService <UnAssignRolesService>();
                SessionFeature.Init(appHost);
            }
        }
示例#3
0
        public void PreAuthenticate(IRequest req, IResponse res)
        {
            var digestAuth = req.GetDigestAuth();

            if (digestAuth != null)
            {
                //Need to run SessionFeature filter since its not executed before this attribute (Priority -100)
                SessionFeature.AddSessionIdToRequestFilter(req, res, null); //Required to get req.GetSessionId()

                using (var authService = HostContext.ResolveService <AuthenticateService>(req))
                {
                    var response = authService.Post(new Authenticate
                    {
                        provider = Name,
                        nonce    = digestAuth["nonce"],
                        uri      = digestAuth["uri"],
                        response = digestAuth["response"],
                        qop      = digestAuth["qop"],
                        nc       = digestAuth["nc"],
                        cnonce   = digestAuth["cnonce"],
                        UserName = digestAuth["username"]
                    });
                }
            }
        }
        public virtual async Task PreAuthenticateWithApiKeyAsync(IRequest req, IResponse res, ApiKey apiKey)
        {
            if (RequireSecureConnection && !req.IsSecureConnection)
            {
                throw HttpError.Forbidden(ErrorMessages.ApiKeyRequiresSecureConnection.Localize(req));
            }

            ValidateApiKey(req, apiKey);

            var apiSessionKey = GetSessionKey(apiKey.Id);

            if (await HasCachedSessionAsync(req, apiSessionKey).ConfigAwait())
            {
                req.Items[Keywords.ApiKey] = apiKey;
                return;
            }

            //Need to run SessionFeature filter since its not executed before this attribute (Priority -100)
            SessionFeature.AddSessionIdToRequestFilter(req, res, null); //Required to get req.GetSessionId()

            using var authService = HostContext.ResolveService <AuthenticateService>(req);
            var response = await authService.PostAsync(new Authenticate
            {
                provider = Name,
                UserName = "******",
                Password = apiKey.Id,
            }).ConfigAwait();

            await CacheSessionAsync(req, apiSessionKey);
        }
        public async Task Can_retrieve_TimeToLive_on_IAuthSession()
        {
            IAuthSession session = new CustomAuthSession
            {
                Id         = "sess-1",
                UserAuthId = "1",
                Custom     = "custom"
            };

            var sessionKey = SessionFeature.GetSessionKey(session.Id);
            await Cache.RemoveAsync(sessionKey);

            var ttl = await Cache.GetTimeToLiveAsync(sessionKey);

            Assert.That(ttl, Is.Null);

            await Cache.SetAsync(sessionKey, session);

            ttl = await Cache.GetTimeToLiveAsync(sessionKey);

            Assert.That(ttl.Value, Is.EqualTo(TimeSpan.MaxValue));

            var sessionExpiry = SessionFeature.DefaultSessionExpiry;
            await Cache.SetAsync(sessionKey, session, sessionExpiry);

            ttl = await Cache.GetTimeToLiveAsync(sessionKey);

            Assert.That(ttl.Value, Is.GreaterThan(TimeSpan.FromSeconds(0)));
            Assert.That(ttl.Value, Is.LessThan(sessionExpiry).
                        Or.EqualTo(sessionExpiry).Within(TimeSpan.FromSeconds(1)));
        }
示例#6
0
        public void Can_retrieve_TimeToLive_on_IAuthSession()
        {
            IAuthSession session = new CustomAuthSession
            {
                Id         = "sess-1",
                UserAuthId = "1",
                Custom     = "custom"
            };

            var sessionKey = SessionFeature.GetSessionKey(session.Id);

            Cache.Remove(sessionKey);

            var ttl = Cache.GetTimeToLive(sessionKey);

            Assert.That(ttl, Is.Null);

            Cache.Set(sessionKey, session);
            ttl = Cache.GetTimeToLive(sessionKey);
            Assert.That(ttl.Value, Is.EqualTo(TimeSpan.MaxValue));

            var sessionExpiry = SessionFeature.DefaultSessionExpiry;

            Cache.Set(sessionKey, session, sessionExpiry);
            ttl = Cache.GetTimeToLive(sessionKey);
            var roundedToSec = new TimeSpan(ttl.Value.Ticks - (ttl.Value.Ticks % 1000));

            Assert.That(roundedToSec, Is.GreaterThan(TimeSpan.FromSeconds(0)));
            Assert.That(roundedToSec, Is.LessThanOrEqualTo(sessionExpiry));
        }
示例#7
0
 public virtual T GetSession <T>() where T : class, IAuthSession
 {
     if (userSession != null)
     {
         return((T)userSession);
     }
     return((T)(userSession = SessionFeature.GetOrCreateSession <T>(Cache, Request, Response)));
 }
示例#8
0
 public virtual T GetSession <T>() where T : class, IAuthSession, new()
 {
     if (userSession != null)
     {
         return((T)userSession);
     }
     return((T)(userSession = SessionFeature.GetOrCreateSession <T>(Cache)));
 }
        //public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
        //{
        //    base.OnAuthenticated(authService, this, tokens, authInfo);
        //    ILog log = LogManager.GetLogger(GetType());

        //    var user = session.ConvertTo<User>();
        //    user.Id = (session as CustomUserSession).Uid;

        //    foreach (var authToken in session.ProviderOAuthAccess)
        //    {
        //        if (authToken.Provider == FacebookAuthProvider.Name)
        //        {
        //            user.UserName = authToken.DisplayName;
        //            user.FirstName = authToken.FirstName;
        //            user.LastName = authToken.LastName;
        //            user.Email = authToken.Email;
        //        }
        //    }
        //}

        public override void OnLogout(IServiceBase authService)
        {
            base.OnLogout(authService);
            using (var cache = authService.TryResolve <ICacheClient>())
            {
                var sessionKey = SessionFeature.GetSessionKey(this.Id);
                cache.Remove(sessionKey);
            }
        }
示例#10
0
        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            //Need to run SessionFeature filter since its not executed before this attribute (Priority -100)
            SessionFeature.AddSessionIdToRequestFilter(req, res, null); //Required to get req.GetSessionId()

            req.Items["TriedMyOwnAuthFirst"] = true;                    // let's simulate some sort of auth _before_ relaying to base class.

            base.Execute(req, res, requestDto);
        }
示例#11
0
        public object Get(ResetUserAuth request)
        {
            this.Cache.Remove(SessionFeature.GetSessionKey(Request));

            Db.DeleteAll <UserAuth>();
            Db.DeleteAll <UserOAuthProvider>();

            return(HttpResult.Redirect(Request.UrlReferrer.AbsoluteUri));
        }
示例#12
0
        public bool ValidUpdater(UpdateFulfillment instance, string fulfiller)
        {
            var key         = SessionFeature.GetSessionKey();
            var currentUser = CacheClient.Get <AuthUserSession>(key);

            if (instance.Status == "Completed" && fulfiller != currentUser.UserName)
            {
                return(false);
            }
            return(true);
        }
示例#13
0
        public AuthUserSession CurrentSession()
        {
            var httpCookie = Request.Cookies["X-ESQTV-SID"];

            if (httpCookie != null)
            {
                var currentSession = httpCookie.Value;
                return(Cache.Get <AuthUserSession>(SessionFeature.GetSessionKey(currentSession)));
            }

            return(null);
        }
示例#14
0
        public object Get(ResetUserAuth request)
        {
            this.Cache.Remove(SessionFeature.GetSessionKey(Request));

            Db.DeleteAll <UserAuth>();
            Db.DeleteAll <UserAuthDetails>();

            var referrer = Request.UrlReferrer != null
                ? Request.UrlReferrer.AbsoluteUri
                : HostContext.Config.WebHostUrl;

            return(HttpResult.Redirect(referrer));
        }
示例#15
0
        public object Get(ResetUserAuth request)
        {
            this.Cache.Remove(SessionFeature.GetSessionKey(Request));

            Db.DeleteAll <UserAuth>();
            Db.DeleteAll <UserAuthDetails>();

            var referrer = Request.UrlReferrer != null
                ? Request.UrlReferrer.AbsoluteUri
                : HttpHandlerFactory.GetBaseUrl();

            return(HttpResult.Redirect(referrer));
        }
示例#16
0
        /// <summary>
        /// Logg off and clear session in service stack.
        /// </summary>
        public void ServiceStackLogOff()
        {
            try
            {
                var httpCookie = Request.Cookies["X-ESQTV-SID"];
                if (httpCookie != null)
                {
                    var currentSession = httpCookie.Value;
                    Cache.Remove(SessionFeature.GetSessionKey(currentSession));
                }
            }

            catch { }
        }
        private static void PreAuthenticateWithApiKey(IRequest req, IResponse res, string apiKey)
        {
            //Need to run SessionFeature filter since its not executed before this attribute (Priority -100)
            SessionFeature.AddSessionIdToRequestFilter(req, res, null); //Required to get req.GetSessionId()

            using (var authService = HostContext.ResolveService <AuthenticateService>(req))
            {
                var response = authService.Post(new Authenticate
                {
                    provider = Name,
                    UserName = "******",
                    Password = apiKey,
                });
            }
        }
        public IAuthSession CreateSessionFromPayload(IRequest req, JsonObject jwtPayload)
        {
            AssertJwtPayloadIsValid(jwtPayload);

            var sessionId = jwtPayload.GetValue("jid", SessionExtensions.CreateRandomSessionId);
            var session   = SessionFeature.CreateNewSession(req, sessionId);

            session.AuthProvider = Name;
            session.PopulateFromMap(jwtPayload);

            PopulateSessionFilter?.Invoke(session, jwtPayload, req);

            HostContext.AppHost.OnSessionFilter(session, sessionId);
            return(session);
        }
 public static void AddGuidRecordsToCache <T>(IWebEasRepositoryBase repository, IEnumerable <KeyValuePair <string, string> > recordsToCache, string hashId = null)
 {
     if (recordsToCache.Any())
     {
         hashId ??= UrnId.Create <T>(repository.Session.Id);
         repository.Redis.Remove(hashId);
         repository.Redis.SetRangeInHash(hashId, recordsToCache);
         var sessionKey = SessionFeature.GetSessionKey(repository.Session.Id);
         var ttl        = repository.Redis.GetTimeToLive(sessionKey);
         if (ttl.HasValue)
         {
             repository.Redis.ExpireEntryIn(hashId, ttl.Value);
         }
     }
 }
示例#20
0
        public static void Init(IAppHost appHost, Func <IAuthSession> sessionFactory, params AuthConfig[] authConfigs)
        {
            if (authConfigs.Length == 0)
            {
                throw new ArgumentNullException("authConfigs");
            }

            DefaultOAuthProvider = authConfigs[0].Provider;
            DefaultOAuthRealm    = authConfigs[0].AuthRealm;

            AuthConfigs    = authConfigs;
            SessionFactory = sessionFactory;
            appHost.RegisterService <AuthService>();

            SessionFeature.Init(appHost);
        }
        protected virtual TUserSession SessionAs<TUserSession>()
        {
            if (HostContext.TestMode)
            {
                var mockSession = TryResolve<TUserSession>();
                if (Equals(mockSession, default(TUserSession)))
                    mockSession = TryResolve<IAuthSession>() is TUserSession
                        ? (TUserSession) TryResolve<IAuthSession>()
                        : default(TUserSession);

                if (!Equals(mockSession, default(TUserSession)))
                    return mockSession;
            }

            return SessionFeature.GetOrCreateSession<TUserSession>(Cache, Request, Response);
        }
        public void PreAuthenticateWithApiKey(IRequest req, IResponse res, ApiKey apiKey)
        {
            if (RequireSecureConnection && !req.IsSecureConnection)
            {
                throw HttpError.Forbidden(ErrorMessages.ApiKeyRequiresSecureConnection.Localize(req));
            }

            ValidateApiKey(req, apiKey);

            var apiSessionKey = GetSessionKey(apiKey.Id);

            if (SessionCacheDuration != null)
            {
                var session = req.GetCacheClient().Get <IAuthSession>(apiSessionKey);

                if (session != null)
                {
                    session = HostContext.AppHost.OnSessionFilter(req, session, session.Id);
                }

                if (session != null)
                {
                    req.Items[Keywords.ApiKey]  = apiKey;
                    req.Items[Keywords.Session] = session;
                    return;
                }
            }

            //Need to run SessionFeature filter since its not executed before this attribute (Priority -100)
            SessionFeature.AddSessionIdToRequestFilter(req, res, null); //Required to get req.GetSessionId()

            using (var authService = HostContext.ResolveService <AuthenticateService>(req))
            {
                var response = authService.Post(new Authenticate
                {
                    provider = Name,
                    UserName = "******",
                    Password = apiKey.Id,
                });
            }

            if (SessionCacheDuration != null)
            {
                var session = req.GetSession();
                req.GetCacheClient().Set(apiSessionKey, session, SessionCacheDuration);
            }
        }
示例#23
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);
                    }
                }
            }
        }
示例#24
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);
                    }
                }
            }
        }
        public async Task Index_ReturnsCartItems_WhenItemsInCart()
        {
            // Arrange
            var cartId         = "CartId_A";
            var sessionFeature = new SessionFeature()
            {
                Session = CreateTestSession(),
            };

            var httpContext = new DefaultHttpContext();

            httpContext.SetFeature <ISessionFeature>(sessionFeature);
            httpContext.Session.SetString("Session", cartId);

            var dbContext = _serviceProvider.GetRequiredService <MusicStoreContext>();
            var cartItems = CreateTestCartItems(
                cartId,
                itemPrice: 10,
                numberOfItem: 5);

            dbContext.AddRange(cartItems.Select(n => n.Album).Distinct());
            dbContext.AddRange(cartItems);
            dbContext.SaveChanges();

            var controller = new ShoppingCartController()
            {
                DbContext = dbContext,
            };

            controller.ActionContext.HttpContext = httpContext;

            // Act
            var result = await controller.Index();

            // Assert
            var viewResult = Assert.IsType <ViewResult>(result);

            Assert.NotNull(viewResult.ViewData);
            Assert.Null(viewResult.ViewName);

            var model = Assert.IsType <ShoppingCartViewModel>(viewResult.ViewData.Model);

            Assert.Equal(5, model.CartItems.Count);
            Assert.Equal(5 * 10, model.CartTotal);
        }
示例#26
0
 public void Register(IAppHost appHost)
 {
     appHost.PreRequestFilters.Add((req, res) =>
     {
         var cultureName = req.GetHeader("X-Culture");
         if (string.IsNullOrEmpty(cultureName))
         {
             cultureName = System.Globalization.CultureInfo.CurrentCulture.Name;
         }
         var culture = System.Globalization.CultureInfo.GetCultureInfo(cultureName);
         System.Threading.Thread.CurrentThread.CurrentCulture   = culture;
         System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
     });
     appHost.GlobalRequestFilters.Add((req, res, requestDto) =>
     {
         SessionFeature.AddSessionIdToRequestFilter(req, res, requestDto);
     });
 }
示例#27
0
 protected bool IsUserAuthorized(IRequest thisRequest)
 {
     try
     {
         // Within the hub itself we can get the request directly from the context.
         //Microsoft.AspNet.SignalR.IRequest myRequest = this.Context.Request; // Unfortunately this is a signalR IRequest, not a ServiceStack IRequest, but we can still use it to get the cookies.
         bool              perm       = thisRequest.Cookies["ss-opt"].Value == "perm";
         string            sessionID  = perm ? thisRequest.Cookies["ss-pid"].Value : thisRequest.Cookies["ss-id"].Value;
         var               sessionKey = SessionFeature.GetSessionKey(sessionID);
         CustomUserSession session    = HostContext.Cache.Get <CustomUserSession>(sessionKey);
         return(session.IsAuthenticated);
     }
     catch (Exception ex)
     {
         // probably not auth'd so no cookies, session etc.
     }
     return(false);
 }
        public void PreAuthenticate(IRequest req, IResponse res)
        {
            var signature = req.Headers[WebhookEventConstants.SecretSignatureHeaderName];

            if (signature.HasValue())
            {
                if (RequireSecureConnection && !req.IsSecureConnection)
                {
                    throw HttpError.Forbidden(Resources.HmacAuthProvider_NotHttps);
                }

                var eventName = req.Headers[WebhookEventConstants.EventNameHeaderName];
                if (OnGetSecret != null)
                {
                    Secret = OnGetSecret(req, eventName);
                }
                if (!Secret.HasValue())
                {
                    throw HttpError.Unauthorized(Resources.HmacAuthProvider_IncorrectlyConfigured);
                }

                var isValidSecret = req.VerifySignature(signature, Secret);
                if (!isValidSecret)
                {
                    throw new HttpError(HttpStatusCode.Unauthorized);
                }

                var requestId = req.Headers[WebhookEventConstants.RequestIdHeaderName];
                var userId    = requestId.HasValue() ? requestId : Guid.NewGuid().ToString("N");
                var username  = req.GetUrlHostName();

                var sessionId = SessionExtensions.CreateRandomSessionId();
                var session   = SessionFeature.CreateNewSession(req, sessionId);
                session.UserAuthId      = userId;
                session.UserAuthName    = username;
                session.UserName        = username;
                session.IsAuthenticated = true;
                session.CreatedAt       = SystemTime.UtcNow;

                HostContext.AppHost.OnSessionFilter(req, session, sessionId);

                req.Items[Keywords.Session] = session;
            }
        }
示例#29
0
        public void PreAuthenticate(IRequest req, IResponse res)
        {
            //Need to run SessionFeature filter since its not executed before this attribute (Priority -100)
            SessionFeature.AddSessionIdToRequestFilter(req, res, null); //Required to get req.GetSessionId()

            var userPass = req.GetBasicAuthUserAndPassword();

            if (userPass != null)
            {
                var authService = req.TryResolve <AuthenticateService>();
                authService.Request = req;
                var response = authService.Post(new Authenticate
                {
                    provider = Name,
                    UserName = userPass.Value.Key,
                    Password = userPass.Value.Value
                });
            }
        }
示例#30
0
        public virtual void PreAuthenticate(IRequest req, IResponse res)
        {
            //API Keys are sent in Basic Auth Username and Password is Empty
            var userPass = req.GetBasicAuthUserAndPassword();

            if (!string.IsNullOrEmpty(userPass?.Value))
            {
                //Need to run SessionFeature filter since its not executed before this attribute (Priority -100)
                SessionFeature.AddSessionIdToRequestFilter(req, res, null); //Required to get req.GetSessionId()

                using var authService = HostContext.ResolveService <AuthenticateService>(req);
                var response = authService.Post(new Authenticate
                {
                    provider = Name,
                    UserName = userPass.Value.Key,
                    Password = userPass.Value.Value
                });
            }
        }