public static IntegrationConfiguration CreateFakeConfiguration(StormpathConfiguration config)
        {
            if (config.Client?.ApiKey == null)
            {
                if (config.Client == null)
                {
                    config.Client = new ClientConfiguration();
                }

                config.Client.ApiKey = new ClientApiKeyConfiguration()
                {
                    Id     = "foo",
                    Secret = "bar"
                };
            }
            ;

            var compiledConfig = Configuration.ConfigurationLoader.Initialize().Load(config);

            var integrationConfig = new IntegrationConfiguration(
                compiledConfig,
                new TenantConfiguration("foo", false, false),
                new KeyValuePair <string, ProviderConfiguration> [0]);

            return(integrationConfig);
        }
 public StormpathTokenExchanger(
     IClient client,
     IApplication application,
     StormpathConfiguration configuration,
     ILogger logger)
 {
     _client        = client;
     _application   = application;
     _configuration = configuration;
     _logger        = logger;
 }
Пример #3
0
 public RegisterExecutor(
     IClient client,
     StormpathConfiguration configuration,
     HandlerConfiguration handlers,
     ILogger logger)
 {
     _client        = client;
     _configuration = configuration;
     _handlers      = handlers;
     _logger        = logger;
 }
        private static void AddStormpathVariablesToEnvironment(
            IDictionary <string, object> environment,
            StormpathConfiguration configuration,
            IClient client,
            IAccount currentUser)
        {
            environment[OwinKeys.StormpathConfiguration] = configuration;
            environment[OwinKeys.StormpathClient]        = client;

            if (currentUser != null)
            {
                environment[OwinKeys.StormpathUser] = currentUser;
            }
        }
Пример #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add Stormpath services
            var stormpathConfiguration = new StormpathConfiguration()
            {
                Web = new WebConfiguration()
                {
                    Login = new WebLoginRouteConfiguration()
                    {
                        View = "~/Views/Stormpath/MyLogin.cshtml"
                    }
                }
            };

            services.AddStormpath(stormpathConfiguration);

            // Add framework services.
            services.AddMvc();
        }
        /// <summary>
        /// Creates a new instance of the <see cref="RouteProtector"/> class.
        /// </summary>
        /// <param name="client">The Stormpath <see cref="IClient">Client</see>.</param>
        /// <param name="stormpathConfiguration">The active Stormpath <see cref="StormpathConfiguration">configuration</see>.</param>
        /// <param name="deleteCookieAction">Delegate to delete cookies in the response.</param>
        /// <param name="setStatusCodeAction">Delegate to set the response status code.</param>
        /// <param name="setHeaderAction">Delegate to set a header in the response.</param>
        /// <param name="redirectAction">Delegate to set the response Location header.</param>
        /// <param name="logger">The <see cref="ILogger"/> to use.</param>
        public RouteProtector(
            IClient client,
            StormpathConfiguration stormpathConfiguration,
            Action <WebCookieConfiguration> deleteCookieAction,
            Action <int> setStatusCodeAction,
            Action <string, string> setHeaderAction,
            Action <string> redirectAction,
            ILogger logger)
        {
            // TODO: remove after splitting out JWT stuff
            _client = client;

            _configuration = stormpathConfiguration;
            _logger        = logger;

            _deleteCookie  = deleteCookieAction;
            _setStatusCode = setStatusCodeAction;
            _setHeader     = setHeaderAction;
            _redirect      = redirectAction;
        }
        public void NotThrowForMissingFieldTypeOnFormResubmission()
        {
            var client = Substitute.For <IClient>();
            var config = new StormpathConfiguration()
            {
                Web = new WebConfiguration
                {
                    Register = new WebRegisterRouteConfiguration
                    {
                        Form = new WebRegisterRouteFormConfiguration
                        {
                            Fields = new Dictionary <string, WebFieldConfiguration>
                            {
                                ["CustomFieldsRock"] = new WebFieldConfiguration {
                                    Required = true
                                }
                            }
                        }
                    }
                }
            };

            var previousFormData = new Dictionary <string, string[]>()
            {
                ["st"]               = new [] { "blah" },
                ["givenName"]        = new [] { "Galen" },
                ["surname"]          = new[] { "Erso" },
                ["CustomFieldsRock"] = new [] { "indeed" }
            };

            var viewModelBuilder = new RegisterFormViewModelBuilder(
                client,
                ConfigurationHelper.CreateFakeConfiguration(config),
                new Dictionary <string, string[]>(),
                previousFormData,
                logger: null);

            var result = viewModelBuilder.Build();

            result.Form.Fields.Should().Contain(x => x.Name == "CustomFieldsRock" && x.Required);
        }
Пример #8
0
        private static IntegrationConfiguration GetIntegrationConfiguration(
            IClient client,
            StormpathConfiguration updatedConfiguration,
            IApplication application,
            ILogger logger)
        {
            var defaultAccountStore     = application.GetDefaultAccountStore();
            var defaultAccountStoreHref = defaultAccountStore?.Href;

            logger.Trace("Default account store href: " + (string.IsNullOrEmpty(defaultAccountStoreHref) ? "<null>" : defaultAccountStoreHref), nameof(GetIntegrationConfiguration));

            var defaultAccountStoreDirectory = defaultAccountStore as IDirectory;

            bool emailVerificationEnabled = false;
            bool passwordResetEnabled     = false;

            if (defaultAccountStoreDirectory != null)
            {
                var accountCreationPolicy = defaultAccountStoreDirectory.GetAccountCreationPolicy();
                emailVerificationEnabled = accountCreationPolicy.VerificationEmailStatus == SDK.Mail.EmailStatus.Enabled;
                logger.Trace($"Got AccountCreationPolicy. Email workflow enabled: {emailVerificationEnabled}", nameof(GetIntegrationConfiguration));

                var passwordPolicy = defaultAccountStoreDirectory.GetPasswordPolicy();
                passwordResetEnabled = passwordPolicy.ResetEmailStatus == SDK.Mail.EmailStatus.Enabled;
                logger.Trace($"Got PasswordPolicy. Reset workflow enabled: {passwordResetEnabled}", nameof(GetIntegrationConfiguration));
            }

            logger.Trace("Getting social providers from tenant...", nameof(GetIntegrationConfiguration));

            var socialProviders = GetSocialProviders(application, updatedConfiguration.Web, logger)
                                  .ToList();

            logger.Trace($"Found {socialProviders.Count} social providers", nameof(GetIntegrationConfiguration));

            return(new IntegrationConfiguration(
                       updatedConfiguration,
                       new TenantConfiguration(defaultAccountStoreHref, emailVerificationEnabled, passwordResetEnabled),
                       socialProviders));
        }
        public static void AddTokenCookiesToResponse(IOwinEnvironment context, IClient client, IOauthGrantAuthenticationResult grantResult, StormpathConfiguration configuration, ILogger logger)
        {
            if (!string.IsNullOrEmpty(grantResult.AccessTokenString))
            {
                var expirationDate = client.NewJwtParser().Parse(grantResult.AccessTokenString).Body.Expiration;
                SetTokenCookie(context, configuration.Web.AccessTokenCookie, grantResult.AccessTokenString, expirationDate, IsSecureRequest(context), logger);
            }

            if (!string.IsNullOrEmpty(grantResult.RefreshTokenString))
            {
                var expirationDate = client.NewJwtParser().Parse(grantResult.RefreshTokenString).Body.Expiration;
                SetTokenCookie(context, configuration.Web.RefreshTokenCookie, grantResult.RefreshTokenString, expirationDate, IsSecureRequest(context), logger);
            }
        }
Пример #10
0
        public static StormpathMiddleware Create(StormpathOwinOptions options)
        {
            if (string.IsNullOrEmpty(options.LibraryUserAgent))
            {
                throw new ArgumentNullException(nameof(options.LibraryUserAgent));
            }

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

            // Construct the framework User-Agent
            IFrameworkUserAgentBuilder userAgentBuilder = new DefaultFrameworkUserAgentBuilder(options.LibraryUserAgent);

            options.Logger.Info("Stormpath middleware starting up", nameof(StormpathMiddleware));

            // Initialize and warm up SDK
            options.Logger.Trace("Initializing and warming up SDK...", nameof(StormpathMiddleware));
            var clientFactory = InitializeClient(options.Configuration, options.ConfigurationFileRoot, options.CacheProvider, options.Logger);

            // Scope a client for our resolution steps below
            options.Logger.Trace("Creating scoped ClientFactory...", nameof(StormpathMiddleware));
            var client = clientFactory.Create(new ScopedClientOptions()
            {
                UserAgent = userAgentBuilder.GetUserAgent()
            });

            // Resolve application href, if necessary
            // (see https://github.com/stormpath/stormpath-framework-spec/blob/master/configuration.md#application-resolution)
            options.Logger.Trace("Resolving application...", nameof(StormpathMiddleware));
            var application = ResolveApplication(client, options.Logger);

            var updatedConfiguration = new StormpathConfiguration(
                client.Configuration.Client,
                new ApplicationConfiguration(application.Name, application.Href),
                client.Configuration.Web);

            // Pull some configuration from the tenant environment
            options.Logger.Trace("Examining tenant environment...", nameof(StormpathMiddleware));
            var integrationConfiguration = GetIntegrationConfiguration(client, updatedConfiguration, application, options.Logger);

            // Validate Account Store configuration
            // (see https://github.com/stormpath/stormpath-framework-spec/blob/master/configuration.md#application-resolution)
            options.Logger.Trace("Ensuring the Account Store configuration is valid...", nameof(StormpathMiddleware));
            EnsureAccountStores(client, integrationConfiguration, application, options.Logger);

            // Validate any remaining configuration
            options.Logger.Trace("Ensuring the integration configuration is valid...", nameof(StormpathMiddleware));
            EnsureIntegrationConfiguration(integrationConfiguration, options.Logger);

            options.Logger.Trace("Stormpath middleware ready!", nameof(StormpathMiddleware));

            var handlerConfiguration = new HandlerConfiguration(
                options.PreChangePasswordHandler ?? DefaultHandlers.PreChangePasswordHandler,
                options.PostChangePasswordHandler ?? DefaultHandlers.PostChangePasswordHandler,
                options.PreLoginHandler ?? DefaultHandlers.PreLoginHandler,
                options.PostLoginHandler ?? DefaultHandlers.PostLoginHandler,
                options.PreLogoutHandler ?? DefaultHandlers.PreLogoutHandler,
                options.PostLogoutHandler ?? DefaultHandlers.PostLogoutHandler,
                options.PreRegistrationHandler ?? DefaultHandlers.PreRegistrationHandler,
                options.PostRegistrationHandler ?? DefaultHandlers.PostRegistrationHandler,
                options.PreVerifyEmailHandler ?? DefaultHandlers.PreVerifyEmailHandler,
                options.PostVerifyEmailHandler ?? DefaultHandlers.PostVerifyEmailHandler);

            return(new StormpathMiddleware(
                       options.ViewRenderer,
                       options.Logger,
                       userAgentBuilder,
                       clientFactory,
                       integrationConfiguration,
                       handlerConfiguration));
        }
 public StormpathConfiguration(StormpathConfiguration existing)
     : this(client: existing?.Client,
           application: existing?.Application,
           web: existing?.Web)
 {
 }
Пример #12
0
 public IntegrationConfiguration(StormpathConfiguration existing, TenantConfiguration tenantConfiguration, IEnumerable <KeyValuePair <string, ProviderConfiguration> > providers)
     : base(existing)
 {
     this.Tenant    = tenantConfiguration;
     this.Providers = providers.ToArray();
 }
Пример #13
0
        public async Task RedirectToNextUriIfAutologinIsEnabled()
        {
            // Arrange
            var config = new StormpathConfiguration()
            {
                Web = new WebConfiguration()
                {
                    Register = new WebRegisterRouteConfiguration()
                    {
                        AutoLogin = true,
                        // default NextUri
                    }
                }
            };
            var fixture = new OwinTestFixture()
            {
                Options = new StormpathOwinOptions()
                {
                    Configuration = config
                }
            };
            var server = Helpers.CreateServer(fixture);

            using (var cleanup = new AutoCleanup(fixture.Client))
            {
                var application = await fixture.Client.GetApplicationAsync(fixture.ApplicationHref);

                var csrfToken = await CsrfToken.GetTokenForRoute(server, "/register");

                var email = $"its-{fixture.TestKey}@testmail.stormpath.com";

                var payload = new Dictionary <string, string>()
                {
                    ["email"]     = email,
                    ["password"]  = "******",
                    ["givenName"] = nameof(RedirectToLogin),
                    ["surname"]   = nameof(RegisterRouteShould),
                    ["st"]        = csrfToken,
                };

                var request = new HttpRequestMessage(HttpMethod.Post, "/register")
                {
                    Content = new FormUrlEncodedContent(payload)
                };
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));

                // Act
                var response = await server.SendAsync(request);

                var foundAccount = await application.GetAccounts().Where(a => a.Email == email).SingleOrDefaultAsync();

                if (foundAccount != null)
                {
                    cleanup.MarkForDeletion(foundAccount);
                }

                // Assert
                response.StatusCode.Should().Be(HttpStatusCode.Redirect);
                response.Headers.Location.ToString().Should().StartWith("/"); // default NextUri
                response.Headers.GetValues("Set-Cookie").Should().Contain(x => x.StartsWith("access_token="));
                response.Headers.GetValues("Set-Cookie").Should().Contain(x => x.StartsWith("refresh_token="));
            }
        }