Ejemplo n.º 1
0
        /// <summary>
        /// Saves the Auth Tokens for this request. Called in OnAuthenticated().
        /// Overrideable, the default behaviour is to call IUserAuthRepository.CreateOrMergeAuthSession().
        /// </summary>
        protected virtual void SaveUserAuth(IServiceBase authService, IAuthSession session, IAuthRepository authRepo, IAuthTokens tokens)
        {
            if (authRepo == null)
            {
                return;
            }
            if (tokens != null)
            {
                session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens).UserAuthId.ToString();
            }

            authRepo.LoadUserAuth(session, tokens);

            foreach (var oAuthToken in session.GetAuthTokens())
            {
                var authProvider     = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                var userAuthProvider = authProvider as OAuthProvider;
                userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken);
            }

            authRepo.SaveUserAuth(session);

            var httpRes = authService.Request.Response as IHttpResponse;

            httpRes?.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
            OnSaveUserAuth(authService, session);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Sets the CallbackUrl and session.ReferrerUrl if not set and initializes the session tokens for this AuthProvider
        /// </summary>
        /// <param name="authService"></param>
        /// <param name="session"></param>
        /// <param name="request"> </param>
        /// <returns></returns>
        protected IAuthTokens Init(IServiceBase authService, ref IAuthSession session, Authenticate request)
        {
            AssertValidState();

            if (this.CallbackUrl.IsNullOrEmpty())
            {
                this.CallbackUrl = authService.Request.AbsoluteUri;
            }

            if (RestoreSessionFromState == true)
            {
                var state = authService.Request.GetQueryStringOrForm(Keywords.State);
                if (!string.IsNullOrEmpty(state))
                {
                    (authService.Request.Response as IHttpResponse)?.ClearCookies();
                    authService.Request.CreateTemporarySessionId(state);
                    session = authService.Request.GetSession(reload: true);
                }
            }

            session.ReferrerUrl = GetReferrerUrl(authService, session, request);

            var tokens = session.GetAuthTokens(Provider);

            if (tokens == null)
            {
                session.AddAuthToken(tokens = new AuthTokens {
                    Provider = Provider
                });
            }

            return(tokens);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// The specified <paramref name="session"/> may change as a side-effect of this method. If
        /// subsequent code relies on current <see cref="IAuthSession"/> data be sure to reload
        /// the session istance via <see cref="ServiceExtensions.GetSession(IServiceBase,bool)"/>.
        /// </summary>
        private object Authenticate(Authenticate request, string provider, IAuthSession session, IAuthProvider oAuthConfig)
        {
            if (request.provider == null && request.UserName == null)
            {
                return(null); //Just return sessionInfo if no provider or username is given
            }
            var authFeature        = HostContext.GetPlugin <AuthFeature>();
            var generateNewCookies = authFeature == null || authFeature.GenerateNewSessionCookiesOnAuthentication;

            object response = null;

            if (!oAuthConfig.IsAuthorized(session, session.GetAuthTokens(provider), request))
            {
                if (generateNewCookies)
                {
                    this.Request.GenerateNewSessionCookies(session);
                }

                response = oAuthConfig.Authenticate(this, session, request);
            }
            else
            {
                if (generateNewCookies)
                {
                    this.Request.GenerateNewSessionCookies(session);
                    oAuthConfig.SaveSession(this, session, (oAuthConfig as AuthProvider)?.SessionExpiry);
                }
            }
            return(response);
        }
Ejemplo n.º 4
0
        protected IAuthTokens Init(IServiceBase authService, ref IAuthSession session, Authenticate request)
        {
            var requestUri = authService.Request.AbsoluteUri;

            if (this.CallbackUrl.IsNullOrEmpty())
            {
                this.CallbackUrl = requestUri;
            }

            if (session.ReferrerUrl.IsNullOrEmpty())
            {
                session.ReferrerUrl = request?.Continue ?? authService.Request.GetHeader("Referer");
            }

            if (session.ReferrerUrl.IsNullOrEmpty() || session.ReferrerUrl.IndexOf("/auth", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                session.ReferrerUrl = this.RedirectUrl
                                      ?? HostContext.Config.WebHostUrl
                                      ?? requestUri.Substring(0, requestUri.IndexOf("/", "https://".Length + 1, StringComparison.Ordinal));
            }

            var tokens = session.GetAuthTokens(this.Provider);

            if (tokens == null)
            {
                session.AddAuthToken(tokens = new AuthTokens {
                    Provider = this.Provider
                });
            }

            return(tokens);
        }
Ejemplo n.º 5
0
        public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            session.AuthProvider = Name;
            if (session is AuthUserSession userSession)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
                HostContext.TryResolve <IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);
            }

            if (session is IAuthSessionExtended authSession)
            {
                var failed = authSession.Validate(authService, session, tokens, authInfo);
                if (failed != null)
                {
                    authService.RemoveSession();
                    return(failed);
                }
            }

            var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request);

            using (authRepo as IDisposable)
            {
                if (authRepo != null)
                {
                    if (tokens != null)
                    {
                        authInfo.ForEach((x, y) => tokens.Items[x] = y);
                        session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens).UserAuthId.ToString();
                    }

                    foreach (var oAuthToken in session.GetAuthTokens())
                    {
                        var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);

                        var userAuthProvider = authProvider as OAuthProvider;
                        userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken);
                    }

                    var failed = ValidateAccount(authService, authRepo, session, tokens);
                    if (failed != null)
                    {
                        return(failed);
                    }
                }
            }

            try
            {
                session.OnAuthenticated(authService, session, tokens, authInfo);
                AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo);
            }
            finally
            {
                this.SaveSession(authService, session, SessionExpiry);
                authService.Request.Items[Keywords.DidAuthenticate] = true;
            }

            return(null);
        }
Ejemplo n.º 6
0
        // Merge tokens into session when no IAuthRepository exists
        public virtual string CreateOrMergeAuthSession(IAuthSession session, IAuthTokens tokens)
        {
            if (session.UserName.IsNullOrEmpty())
                session.UserName = tokens.UserName;
            if (session.DisplayName.IsNullOrEmpty())
                session.DisplayName = tokens.DisplayName;
            if (session.Email.IsNullOrEmpty())
                session.Email = tokens.Email;

            var oAuthTokens = session.GetAuthTokens(tokens.Provider);
            if (oAuthTokens != null && oAuthTokens.UserId == tokens.UserId)
            {
                if (!oAuthTokens.UserName.IsNullOrEmpty())
                    session.UserName = oAuthTokens.UserName;
                if (!oAuthTokens.DisplayName.IsNullOrEmpty())
                    session.DisplayName = oAuthTokens.DisplayName;
                if (!oAuthTokens.Email.IsNullOrEmpty())
                    session.Email = oAuthTokens.Email;
                if (!oAuthTokens.FirstName.IsNullOrEmpty())
                    session.FirstName = oAuthTokens.FirstName;
                if (!oAuthTokens.LastName.IsNullOrEmpty())
                    session.LastName = oAuthTokens.LastName;
            }

            var key = tokens.Provider + ":" + (tokens.UserId ?? tokens.UserName);
            return transientUserIdsMap.GetOrAdd(key,
                k => Interlocked.Increment(ref transientUserAuthId)).ToString(CultureInfo.InvariantCulture);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Sets the CallbackUrl and session.ReferrerUrl if not set and initializes the session tokens for this AuthProvider
        /// </summary>
        /// <param name="authService"></param>
        /// <param name="session"></param>
        /// <param name="request"> </param>
        /// <returns></returns>
        protected IAuthTokens Init(IServiceBase authService, ref IAuthSession session, Authenticate request)
        {
            if (this.CallbackUrl.IsNullOrEmpty())
            {
                this.CallbackUrl = authService.Request.AbsoluteUri;
            }

            session.ReferrerUrl = GetReferrerUrl(authService, session, request);

            var tokens = session.GetAuthTokens(Provider);

            if (tokens == null)
            {
                session.AddAuthToken(tokens = new AuthTokens {
                    Provider = Provider
                });
            }

            return(tokens);
        }
Ejemplo n.º 8
0
        public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var userSession = session as AuthUserSession;
            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
                HostContext.TryResolve<IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);
            }

            var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request);
            using (authRepo as IDisposable)
            {
                if (authRepo != null)
                {
                    if (tokens != null)
                    {
                        authInfo.ForEach((x, y) => tokens.Items[x] = y);
                        session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens).UserAuthId.ToString();
                    }

                    foreach (var oAuthToken in session.GetAuthTokens())
                    {
                        var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);

                        var userAuthProvider = authProvider as OAuthProvider;
                        userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken);
                    }

                    var failed = ValidateAccount(authService, authRepo, session, tokens);
                    if (failed != null)
                        return failed;
                }
            }

            try
            {
                session.OnAuthenticated(authService, session, tokens, authInfo);
                AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo);
            }
            finally
            {
                this.SaveSession(authService, session, SessionExpiry);
            }

            return null;
        }
Ejemplo n.º 9
0
        public virtual IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var userSession = session as AuthUserSession;
            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
                HostContext.TryResolve<IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);

                LoadUserAuthFilter?.Invoke(userSession, tokens, authInfo);
            }

            var hasTokens = tokens != null && authInfo != null;
            if (hasTokens)
            {
                authInfo.ForEach((x, y) => tokens.Items[x] = y);
            }

            var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request);
            using (authRepo as IDisposable)
            {
                if (CustomValidationFilter != null)
                {
                    var ctx = new AuthContext
                    {
                        Request = authService.Request,
                        Service = authService,
                        AuthProvider = this,
                        Session = session,
                        AuthTokens = tokens,
                        AuthInfo = authInfo,
                        AuthRepository = authRepo,
                    };
                    var response = CustomValidationFilter(ctx);
                    if (response != null)
                    {
                        authService.RemoveSession();
                        return response;
                    }
                }

                if (authRepo != null)
                {
                    var failed = ValidateAccount(authService, authRepo, session, tokens);
                    if (failed != null)
                    {
                        authService.RemoveSession();
                        return failed;
                    }

                    if (hasTokens)
                    {
                        var authDetails = authRepo.CreateOrMergeAuthSession(session, tokens);
                        session.UserAuthId = authDetails.UserAuthId.ToString();

                        var firstTimeAuthenticated = authDetails.CreatedDate == authDetails.ModifiedDate;
                        if (firstTimeAuthenticated)
                        {
                            session.OnRegistered(authService.Request, session, authService);
                            AuthEvents.OnRegistered(authService.Request, session, authService);
                        }
                    }

                    authRepo.LoadUserAuth(session, tokens);

                    foreach (var oAuthToken in session.GetAuthTokens())
                    {
                        var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                        var userAuthProvider = authProvider as OAuthProvider;
                        userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken);
                    }

                    var httpRes = authService.Request.Response as IHttpResponse;
                    if (session.UserAuthId != null)
                    {
                        httpRes?.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
                    }
                }
                else
                {
                    if (hasTokens)
                    {
                        session.UserAuthId = CreateOrMergeAuthSession(session, tokens);
                    }
                }
            }

            try
            {
                session.IsAuthenticated = true;
                session.OnAuthenticated(authService, session, tokens, authInfo);
                AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo);
            }
            finally
            {
                this.SaveSession(authService, session, SessionExpiry);
            }

            return null;
        }
        public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            session.AuthProvider = Provider;

            var userSession = session as AuthUserSession;

            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
                HostContext.TryResolve <IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);
                LoadUserAuthFilter?.Invoke(userSession, tokens, authInfo);
            }

            var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request);

            using (authRepo as IDisposable)
            {
                if (CustomValidationFilter != null)
                {
                    var ctx = new AuthContext
                    {
                        Request        = authService.Request,
                        Service        = authService,
                        AuthProvider   = this,
                        Session        = session,
                        AuthTokens     = tokens,
                        AuthInfo       = authInfo,
                        AuthRepository = authRepo,
                    };
                    var response = CustomValidationFilter(ctx);
                    if (response != null)
                    {
                        authService.RemoveSession();
                        return(response);
                    }
                }

                if (authRepo != null)
                {
                    if (tokens != null)
                    {
                        authInfo.ForEach((x, y) => tokens.Items[x] = y);
                        session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens).UserAuthId.ToString();
                    }

                    foreach (var oAuthToken in session.GetAuthTokens())
                    {
                        var authProvider     = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                        var userAuthProvider = authProvider as OAuthProvider;
                        userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken);
                    }

                    var httpRes = authService.Request.Response as IHttpResponse;
                    httpRes?.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);

                    var failed = ValidateAccount(authService, authRepo, session, tokens);
                    if (failed != null)
                    {
                        return(failed);
                    }
                }
            }

            try
            {
                session.IsAuthenticated = true;
                session.OnAuthenticated(authService, session, tokens, authInfo);
                AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo);
            }
            finally
            {
                this.SaveSession(authService, session, SessionExpiry);
            }

            return(null);
        }
Ejemplo n.º 11
0
        protected IAuthTokens Init(IServiceBase authService, ref IAuthSession session, Authenticate request)
        {
            var requestUri = authService.Request.AbsoluteUri;
            if (this.CallbackUrl.IsNullOrEmpty())
            {
                this.CallbackUrl = requestUri;
            }

            if (session.ReferrerUrl.IsNullOrEmpty())
            {
                session.ReferrerUrl = (request != null ? request.Continue : null) ?? authService.Request.GetHeader("Referer");
            }

            if (session.ReferrerUrl.IsNullOrEmpty() || session.ReferrerUrl.IndexOf("/auth", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                session.ReferrerUrl = this.RedirectUrl
                    ?? HttpHandlerFactory.GetBaseUrl()
                    ?? requestUri.Substring(0, requestUri.IndexOf("/", "https://".Length + 1, StringComparison.Ordinal));
            }

            var tokens = session.GetAuthTokens(this.Provider);
            if (tokens == null)
            {
                session.AddAuthToken(tokens = new AuthTokens { Provider = this.Provider });
            }

            return tokens;
        }
Ejemplo n.º 12
0
        public virtual async Task <IHttpResult> OnAuthenticatedAsync(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default)
        {
            session.AuthProvider = Provider;

            if (session is AuthUserSession userSession)
            {
                await LoadUserAuthInfoAsync(userSession, tokens, authInfo, token).ConfigAwait();

                HostContext.TryResolve <IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);

                LoadUserAuthFilter?.Invoke(userSession, tokens, authInfo);
            }

            var hasTokens = tokens != null && authInfo != null;

            if (hasTokens && SaveExtendedUserInfo)
            {
                if (tokens.Items == null)
                {
                    tokens.Items = new Dictionary <string, string>();
                }

                foreach (var entry in authInfo)
                {
                    if (ExcludeAuthInfoItems.Contains(entry.Key))
                    {
                        continue;
                    }

                    tokens.Items[entry.Key] = entry.Value;
                }
            }

            if (session is IAuthSessionExtended authSession)
            {
                var failed = authSession.Validate(authService, session, tokens, authInfo)
                             ?? AuthEvents.Validate(authService, session, tokens, authInfo);
                if (failed != null)
                {
                    await authService.RemoveSessionAsync(token).ConfigAwait();

                    return(failed);
                }
            }

            var authRepo = GetAuthRepositoryAsync(authService.Request);

#if NET472 || NETSTANDARD2_0
            await using (authRepo as IAsyncDisposable)
#else
            using (authRepo as IDisposable)
#endif
            {
                if (CustomValidationFilter != null)
                {
                    var ctx = new AuthContext
                    {
                        Request             = authService.Request,
                        Service             = authService,
                        AuthProvider        = this,
                        Session             = session,
                        AuthTokens          = tokens,
                        AuthInfo            = authInfo,
                        AuthRepositoryAsync = authRepo,
                        AuthRepository      = authRepo as IAuthRepository,
                    };
                    var response = CustomValidationFilter(ctx);
                    if (response != null)
                    {
                        await authService.RemoveSessionAsync(token).ConfigAwait();

                        return(response);
                    }
                }

                if (authRepo != null)
                {
                    var failed = await ValidateAccountAsync(authService, authRepo, session, tokens, token).ConfigAwait();

                    if (failed != null)
                    {
                        await authService.RemoveSessionAsync(token).ConfigAwait();

                        return(failed);
                    }

                    if (hasTokens)
                    {
                        var authDetails = await authRepo.CreateOrMergeAuthSessionAsync(session, tokens, token).ConfigAwait();

                        session.UserAuthId = authDetails.UserAuthId.ToString();

                        var firstTimeAuthenticated = authDetails.CreatedDate == authDetails.ModifiedDate;
                        if (firstTimeAuthenticated)
                        {
                            session.OnRegistered(authService.Request, session, authService);
                            AuthEvents.OnRegistered(authService.Request, session, authService);
                        }
                    }

                    await authRepo.LoadUserAuthAsync(session, tokens, token).ConfigAwait();

                    foreach (var oAuthToken in session.GetAuthTokens())
                    {
                        var authProvider     = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                        var userAuthProvider = authProvider as OAuthProvider;
                        userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken);
                    }

                    var httpRes = authService.Request.Response as IHttpResponse;
                    if (session.UserAuthId != null)
                    {
                        httpRes?.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
                    }
                }
                else
                {
                    if (hasTokens)
                    {
                        session.UserAuthId = CreateOrMergeAuthSession(session, tokens);
                    }
                }
            }

            try
            {
                session.IsAuthenticated = true;
                session.OnAuthenticated(authService, session, tokens, authInfo);
                AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo);
            }
            finally
            {
                await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait();

                authService.Request.Items[Keywords.DidAuthenticate] = true;
            }

            return(null);
        }
Ejemplo n.º 13
0
        public override async Task <IHttpResult> OnAuthenticatedAsync(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default)
        {
            session.AuthProvider = Name;
            if (session is AuthUserSession userSession)
            {
                await LoadUserAuthInfoAsync(userSession, tokens, authInfo, token).ConfigAwait();

                HostContext.TryResolve <IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);
            }

            if (session is IAuthSessionExtended authSession)
            {
                var failed = authSession.Validate(authService, session, tokens, authInfo)
                             ?? await authSession.ValidateAsync(authService, session, tokens, authInfo, token)
                             ?? AuthEvents.Validate(authService, session, tokens, authInfo)
                             ?? (AuthEvents is IAuthEventsAsync asyncEvents
                        ? await asyncEvents.ValidateAsync(authService, session, tokens, authInfo, token)
                        : null);

                if (failed != null)
                {
                    await authService.RemoveSessionAsync(token).ConfigAwait();

                    return(failed);
                }
            }

            var authRepo = GetUserAuthRepositoryAsync(authService.Request);

#if NET472 || NETSTANDARD2_0
            await using (authRepo as IAsyncDisposable)
#else
            using (authRepo as IDisposable)
#endif
            {
                if (authRepo != null)
                {
                    if (tokens != null)
                    {
                        authInfo.ForEach((x, y) => tokens.Items[x] = y);
                        session.UserAuthId = (await authRepo.CreateOrMergeAuthSessionAsync(session, tokens, token)).UserAuthId.ToString();
                    }

                    foreach (var oAuthToken in session.GetAuthTokens())
                    {
                        var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);

                        var userAuthProvider = authProvider as OAuthProvider;
                        userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken);
                    }

                    var failed = await ValidateAccountAsync(authService, authRepo, session, tokens, token).ConfigAwait();

                    if (failed != null)
                    {
                        return(failed);
                    }
                }
            }

            try
            {
                session.IsAuthenticated = true;
                session.OnAuthenticated(authService, session, tokens, authInfo);
                if (session is IAuthSessionExtended sessionExt)
                {
                    await sessionExt.OnAuthenticatedAsync(authService, session, tokens, authInfo, token).ConfigAwait();
                }
                AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo);
                if (AuthEvents is IAuthEventsAsync asyncEvents)
                {
                    await asyncEvents.OnAuthenticatedAsync(authService.Request, session, authService, tokens, authInfo, token).ConfigAwait();
                }
            }
            finally
            {
                await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait();

                authService.Request.Items[Keywords.DidAuthenticate] = true;
            }

            return(null);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Sets the CallbackUrl and session.ReferrerUrl if not set and initializes the session tokens for this AuthProvider
        /// </summary>
        /// <param name="authService"></param>
        /// <param name="session"></param>
        /// <param name="request"> </param>
        /// <returns></returns>
        protected IAuthTokens Init(IServiceBase authService, ref IAuthSession session, Authenticate request)
        {
            if (this.CallbackUrl.IsNullOrEmpty())
                this.CallbackUrl = authService.Request.AbsoluteUri;

            session.ReferrerUrl = GetReferrerUrl(authService, session, request);

            var tokens = session.GetAuthTokens(Provider);
            if (tokens == null)
                session.AddAuthToken(tokens = new AuthTokens { Provider = Provider });

            return tokens;
        }
Ejemplo n.º 15
0
        // Merge tokens into session when no IAuthRepository exists
        public virtual string CreateOrMergeAuthSession(IAuthSession session, IAuthTokens tokens)
        {
            if (session.UserName.IsNullOrEmpty())
                session.UserName = tokens.UserName;
            if (session.DisplayName.IsNullOrEmpty())
                session.DisplayName = tokens.DisplayName;
            if (session.Email.IsNullOrEmpty())
                session.Email = tokens.Email;

            var oAuthTokens = session.GetAuthTokens(tokens.Provider);
            if (oAuthTokens != null && oAuthTokens.UserId == tokens.UserId)
            {
                if (!oAuthTokens.UserName.IsNullOrEmpty())
                    session.UserName = oAuthTokens.UserName;
                if (!oAuthTokens.DisplayName.IsNullOrEmpty())
                    session.DisplayName = oAuthTokens.DisplayName;
                if (!oAuthTokens.Email.IsNullOrEmpty())
                    session.Email = oAuthTokens.Email;
                if (!oAuthTokens.FirstName.IsNullOrEmpty())
                    session.FirstName = oAuthTokens.FirstName;
                if (!oAuthTokens.LastName.IsNullOrEmpty())
                    session.LastName = oAuthTokens.LastName;
            }

            var key = tokens.Provider + ":" + (tokens.UserId ?? tokens.UserName);
            return transientUserIdsMap.GetOrAdd(key,
                k => Interlocked.Increment(ref transientUserAuthId)).ToString(CultureInfo.InvariantCulture);
        }
Ejemplo n.º 16
0
        public virtual IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            session.AuthProvider = Provider;

            if (session is AuthUserSession userSession)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
                HostContext.TryResolve <IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);

                LoadUserAuthFilter?.Invoke(userSession, tokens, authInfo);
            }

            var hasTokens = tokens != null && authInfo != null;

            if (hasTokens && SaveExtendedUserInfo)
            {
                if (tokens.Items == null)
                {
                    tokens.Items = new Dictionary <string, string>();
                }

                authInfo.ForEach((x, y) => tokens.Items[x] = y);
            }

            var authRepo = GetAuthRepository(authService.Request);

            using (authRepo as IDisposable)
            {
                if (CustomValidationFilter != null)
                {
                    var ctx = new AuthContext
                    {
                        Request        = authService.Request,
                        Service        = authService,
                        AuthProvider   = this,
                        Session        = session,
                        AuthTokens     = tokens,
                        AuthInfo       = authInfo,
                        AuthRepository = authRepo,
                    };
                    var response = CustomValidationFilter(ctx);
                    if (response != null)
                    {
                        authService.RemoveSession();
                        return(response);
                    }
                }

                if (authRepo != null)
                {
                    var failed = ValidateAccount(authService, authRepo, session, tokens);
                    if (failed != null)
                    {
                        authService.RemoveSession();
                        return(failed);
                    }

                    if (hasTokens)
                    {
                        var authDetails = authRepo.CreateOrMergeAuthSession(session, tokens);
                        session.UserAuthId = authDetails.UserAuthId.ToString();

                        var firstTimeAuthenticated = authDetails.CreatedDate == authDetails.ModifiedDate;
                        if (firstTimeAuthenticated)
                        {
                            session.OnRegistered(authService.Request, session, authService);
                            AuthEvents.OnRegistered(authService.Request, session, authService);
                        }
                    }

                    authRepo.LoadUserAuth(session, tokens);

                    foreach (var oAuthToken in session.GetAuthTokens())
                    {
                        var authProvider     = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                        var userAuthProvider = authProvider as OAuthProvider;
                        userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken);
                    }

                    var httpRes = authService.Request.Response as IHttpResponse;
                    if (session.UserAuthId != null)
                    {
                        httpRes?.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
                    }
                }
                else
                {
                    if (hasTokens)
                    {
                        session.UserAuthId = CreateOrMergeAuthSession(session, tokens);
                    }
                }
            }

            try
            {
                session.IsAuthenticated = true;
                session.OnAuthenticated(authService, session, tokens, authInfo);
                AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo);
            }
            finally
            {
                this.SaveSession(authService, session, SessionExpiry);
                authService.Request.Items[Keywords.DidAuthenticate] = true;
            }

            return(null);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// The specified <paramref name="session"/> may change as a side-effect of this method. If
        /// subsequent code relies on current <see cref="IAuthSession"/> data be sure to reload
        /// the session istance via <see cref="ServiceExtensions.GetSession(IServiceBase,bool)"/>.
        /// </summary>
        private object Authenticate(Authenticate request, string provider, IAuthSession session, IAuthProvider oAuthConfig)
        {
            if (request.provider == null && request.UserName == null)
                return null; //Just return sessionInfo if no provider or username is given

            var authFeature = HostContext.GetPlugin<AuthFeature>();
            var generateNewCookies = authFeature == null || authFeature.GenerateNewSessionCookiesOnAuthentication;

            object response = null;
            if (!oAuthConfig.IsAuthorized(session, session.GetAuthTokens(provider), request))
            {
                if (generateNewCookies)
                    this.Request.GenerateNewSessionCookies(session);

                response = oAuthConfig.Authenticate(this, session, request);
            }
            else
            {
                if (generateNewCookies)
                {
                    this.Request.GenerateNewSessionCookies(session);
                    oAuthConfig.SaveSession(this, session, (oAuthConfig as AuthProvider)?.SessionExpiry);
                }
            }
            return response;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Saves the Auth Tokens for this request. Called in OnAuthenticated(). 
        /// Overrideable, the default behaviour is to call IUserAuthRepository.CreateOrMergeAuthSession().
        /// </summary>
        protected virtual void SaveUserAuth(IServiceBase authService, IAuthSession session, IAuthRepository authRepo, IAuthTokens tokens)
        {
            if (authRepo == null) return;
            if (tokens != null)
            {
                session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens).UserAuthId.ToString();
            }

            authRepo.LoadUserAuth(session, tokens);

            foreach (var oAuthToken in session.GetAuthTokens())
            {
                var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                var userAuthProvider = authProvider as OAuthProvider;
                userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken);
            }

            authRepo.SaveUserAuth(session);

            var httpRes = authService.Request.Response as IHttpResponse;
            httpRes?.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
            OnSaveUserAuth(authService, session);
        }