public async Task ReturnDefaultErrorMessageDuringJsonPost()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreLoginHandler = (ctx, ct) =>
                    {
                        ctx.Result = new PreLoginResult()
                        {
                            Success = false
                        };
                        return(Task.FromResult(0));
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

            // Act
            var payload = new
            {
                login    = "******",
                password = "******",
            };

            var response = await server.PostAsync("/login", new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"));

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
            (await response.Content.ReadAsStringAsync()).Should().Contain("An error has occurred. Please try again.");
        }
Esempio n. 2
0
        public async Task ReturnCustomErrorMessageDuringJsonPost()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreRegistrationHandler = (ctx, ct) =>
                    {
                        ctx.Result = new PreRegistrationResult()
                        {
                            Success      = false,
                            ErrorMessage = "Nice try, rebel scum!"
                        };
                        return(Task.FromResult(0));
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

            // Act
            var payload = new
            {
                email     = $"its-{fixture.TestKey}@testmail.stormpath.com",
                password  = "******",
                givenName = "Jyn",
                surname   = "Erso"
            };

            var response = await server.PostAsync("/register", new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"));

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
            (await response.Content.ReadAsStringAsync()).Should().Contain("\"message\": \"Nice try, rebel scum!\"");
        }
Esempio n. 3
0
        public async Task AccessAccount()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreLogoutHandler = async(ctx, ct) =>
                    {
                        ctx.Account.CustomData["micdrop"] = true;
                        await ctx.Account.SaveAsync();
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

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

                var account = await application.CreateAccountAsync(
                    nameof(AccessAccount),
                    nameof(PreLogoutHandlerShould),
                    $"its-{fixture.TestKey}@testmail.stormpath.com",
                    "Changeme123!!");

                cleanup.MarkForDeletion(account);

                var payload = new
                {
                    login    = $"its-{fixture.TestKey}@testmail.stormpath.com",
                    password = "******"
                };

                var loginResponse = await server.PostAsync("/login", new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"));

                loginResponse.EnsureSuccessStatusCode();

                var accessTokenCookie = loginResponse.Headers.GetValues("Set-Cookie")
                                        .First(h => h.StartsWith("access_token="));
                var accessToken = accessTokenCookie.Split(';')[0].Replace("access_token=", string.Empty);

                // Act
                var request = new HttpRequestMessage(HttpMethod.Post, "/logout");
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                request.Content = new FormUrlEncodedContent(new KeyValuePair <string, string> [0]);

                var response = await server.SendAsync(request);

                response.EnsureSuccessStatusCode();

                // Assert
                var customData = await account.GetCustomDataAsync();

                customData["micdrop"].Should().Be(true);
            }
        }
        public async Task RedirectToCustomUri()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PostLoginHandler = (ctx, ct) =>
                    {
                        ctx.Result = new PostLoginResult
                        {
                            RedirectUri = "/foobar"
                        };
                        return(Task.FromResult(true));
                    }
                }
            };
            var server    = Helpers.CreateServer(fixture);
            var csrfToken = await CsrfToken.GetTokenForRoute(server, "/login");

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

                var email   = $"its-{fixture.TestKey}@testmail.stormpath.com";
                var account = await application.CreateAccountAsync(
                    nameof(RedirectToCustomUri),
                    nameof(PostLoginHandlerShould),
                    email,
                    "Changeme123!!");

                cleanup.MarkForDeletion(account);

                var payload = new Dictionary <string, string>()
                {
                    ["login"]    = email,
                    ["password"] = "******",
                    ["st"]       = csrfToken,
                };

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

                var response = await server.SendAsync(request);

                // Assert
                response.StatusCode.Should().Be(HttpStatusCode.Redirect);
                response.Headers.Location.ToString().Should().Be("/foobar");
            }
        }
        public async Task SpecifyAccountStore()
        {
            // Arrange
            var directoryName = $"AnotherDirectory {Guid.NewGuid()}";

            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreLoginHandler = async(ctx, ct) =>
                    {
                        ctx.AccountStore = await ctx.Client.GetDirectories().Where(d => d.Name == directoryName).SingleAsync();
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

            using (var cleanup = new AutoCleanup(fixture.Client))
            {
                // Create a directory
                var createdDirectory = await fixture.Client.CreateDirectoryAsync(directoryName, $"Test {fixture.TestKey}", DirectoryStatus.Enabled);

                cleanup.MarkForDeletion(createdDirectory);

                // Create an account in the accountStore
                await createdDirectory.CreateAccountAsync(
                    nameof(SpecifyAccountStore),
                    nameof(PreLoginHandlerShould),
                    $"its-{fixture.TestKey}@testmail.stormpath.com",
                    "Changeme123!!");

                // Account will be deleted along with directory

                // Associate the directory with our application
                var application = await fixture.Client.GetApplicationAsync(fixture.ApplicationHref);

                await application.AddAccountStoreAsync(createdDirectory);

                var payload = new Dictionary <string, string>()
                {
                    ["grant_type"] = "password",
                    ["username"]   = $"its-{fixture.TestKey}@testmail.stormpath.com",
                    ["password"]   = "******"
                };

                // Act
                var response = await server.PostAsync("/oauth/token", new FormUrlEncodedContent(payload));

                // Assert
                response.IsSuccessStatusCode.Should().BeTrue();
            }
        }
Esempio n. 6
0
        public async Task SpecifyOrganizationByNameKey()
        {
            // Arrange
            var orgNameKey = $"TestOrg-{Guid.NewGuid()}";

            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreRegistrationHandler = (ctx, ct) =>
                    {
                        ctx.OrganizationNameKey = orgNameKey;
                        return(Task.CompletedTask);
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

            using (var cleanup = new AutoCleanup(fixture.Client))
            {
                // Create an organization
                var org = fixture.Client.Instantiate <IOrganization>()
                          .SetName($"Test Organization {fixture.TestKey}")
                          .SetNameKey(orgNameKey);
                await fixture.Client.CreateOrganizationAsync(org, opt => opt.CreateDirectory = true);

                cleanup.MarkForDeletion(org);

                var createdDirectory = await fixture.Client.GetDirectories().Where(dir => dir.Name.StartsWith($"Test Organization {fixture.TestKey}")).SingleAsync();

                //cleanup.MarkForDeletion(directory); // TODO

                var email   = $"its-{fixture.TestKey}@testmail.stormpath.com";
                var payload = new
                {
                    email,
                    password  = "******",
                    givenName = "Chewbacca",
                    surname   = "Wookiee"
                };

                var response = await server.PostAsync("/register", new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"));

                response.EnsureSuccessStatusCode();

                var account = await org.GetAccounts().Where(a => a.Email == email).SingleAsync();

                account.Should().NotBeNull();
                cleanup.MarkForDeletion(account);
            }
        }
        public async Task RedirectToDeepLinkUriViaStateToken()
        {
            // Arrange
            var fixture = new OwinTestFixture();
            var server  = Helpers.CreateServer(fixture);

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

                var email   = $"its-{fixture.TestKey}@testmail.stormpath.com";
                var account = await application.CreateAccountAsync(
                    nameof(RedirectToCustomUri),
                    nameof(PostLoginHandlerShould),
                    email,
                    "Changeme123!!");

                cleanup.MarkForDeletion(account);

                var stateToken = fixture.Client.NewJwtBuilder()
                                 .SetClaims(new Dictionary <string, object>()
                {
                    ["state"] = Guid.NewGuid().ToString(),
                    ["path"]  = "/zomg"
                })
                                 .SetExpiration(DateTimeOffset.UtcNow.AddMinutes(1))
                                 .SignWith(fixture.Client.Configuration.Client.ApiKey.Secret, Encoding.UTF8)
                                 .Build()
                                 .ToString();

                var payload = new Dictionary <string, string>()
                {
                    ["login"]    = email,
                    ["password"] = "******",
                    ["st"]       = stateToken,
                };

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

                var response = await server.SendAsync(request);

                // Assert
                response.StatusCode.Should().Be(HttpStatusCode.Redirect);
                response.Headers.Location.ToString().Should().Be("/zomg");
            }
        }
Esempio n. 8
0
        public async Task AcceptRequestWithNoContentType()
        {
            // Arrange
            var fixture = new OwinTestFixture();
            var server  = Helpers.CreateServer(fixture);

            // Act
            var request = new HttpRequestMessage(HttpMethod.Post, "/logout");

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = await server.SendAsync(request);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.OK);
        }
        public async Task AccessAccount()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreChangePasswordHandler = async(ctx, ct) =>
                    {
                        ctx.Account.CustomData["favoriteDroid"] = "R2-D2";
                        await ctx.Account.SaveAsync();
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

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

                var email   = $"its-{fixture.TestKey}@testmail.stormpath.com";
                var account = await application.CreateAccountAsync(
                    nameof(AccessAccount),
                    nameof(PreChangePasswordHandlerShould),
                    email,
                    "Changeme123!!");

                cleanup.MarkForDeletion(account);

                var token = await application.SendPasswordResetEmailAsync(email);

                var payload = new
                {
                    sptoken  = token.GetValue(),
                    password = "******"
                };

                // Act
                var response = await server.PostAsync("/change", new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"));

                response.EnsureSuccessStatusCode();

                // Assert
                var customData = await account.GetCustomDataAsync();

                customData["favoriteDroid"].Should().Be("R2-D2");
            }
        }
Esempio n. 10
0
        public async Task RejectRequestsWhenPasswordGrantDisabled()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    Configuration = new StormpathConfiguration
                    {
                        Web = new WebConfiguration
                        {
                            Oauth2 = new WebOauth2RouteConfiguration
                            {
                                Password = new WebOauth2PasswordGrantConfiguration
                                {
                                    Enabled = false
                                }
                            }
                        }
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

            var payload = new Dictionary <string, string>()
            {
                ["grant_type"] = "password",
                ["username"]   = "******",
                ["password"]   = "******"
            };

            // Act
            var request = new HttpRequestMessage(HttpMethod.Post, "/oauth/token")
            {
                Content = new FormUrlEncodedContent(payload)
            };

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = await server.SendAsync(request);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
            var body = JsonConvert.DeserializeObject <Dictionary <string, string> >(await response.Content.ReadAsStringAsync());

            body["error"].Should().Be("unsupported_grant_type");
        }
        public async Task AccessAccount()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PostRegistrationHandler = async(ctx, ct) =>
                    {
                        ctx.Account.CustomData["homeworld"] = "Alderaan";
                        await ctx.Account.SaveAsync();
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

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

                // Act
                var email   = $"its-{fixture.TestKey}@testmail.stormpath.com";
                var payload = new
                {
                    email,
                    password  = "******",
                    givenName = "Princess",
                    surname   = "Leia"
                };

                var response = await server.PostAsync("/register", new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"));

                response.EnsureSuccessStatusCode();

                var account = await application.GetAccounts().Where(a => a.Email == email).SingleAsync();

                cleanup.MarkForDeletion(account);

                // Assert
                var customData = await account.GetCustomDataAsync();

                customData["homeworld"].Should().Be("Alderaan");
            }
        }
Esempio n. 12
0
        public async Task ReturnCustomErrorMessageDuringFormPost()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreRegistrationHandler = (ctx, ct) =>
                    {
                        ctx.Result = new PreRegistrationResult()
                        {
                            Success      = false,
                            ErrorMessage = "Nice try, rebel scum!"
                        };
                        return(Task.FromResult(0));
                    }
                }
            };
            var server    = Helpers.CreateServer(fixture);
            var csrfToken = await CsrfToken.GetTokenForRoute(server, "/register");

            // Act
            var payload = new Dictionary <string, string>()
            {
                ["email"]     = $"its-{fixture.TestKey}@testmail.stormpath.com",
                ["password"]  = "******",
                ["givenName"] = "Jyn",
                ["surname"]   = "Erso",
                ["st"]        = csrfToken,
            };

            var request = new HttpRequestMessage(HttpMethod.Post, "/register")
            {
                Content = new FormUrlEncodedContent(payload)
            };

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));

            var response = await server.SendAsync(request);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.OK);
            (await response.Content.ReadAsStringAsync()).Should().Contain("Nice try, rebel scum!");
        }
Esempio n. 13
0
        public async Task RedirectToLogin()
        {
            // Arrange
            var fixture = new OwinTestFixture(); // all default settings
            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("/login?status=created");
            }
        }
Esempio n. 14
0
        public async Task RejectUnknownCustomFieldOnFormPost()
        {
            // Arrange
            var fixture   = new OwinTestFixture();
            var server    = Helpers.CreateServer(fixture);
            var csrfToken = await CsrfToken.GetTokenForRoute(server, "/register");

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

                // Act
                var email = $"its-{fixture.TestKey}@testmail.stormpath.com";
                // Act
                var payload = new Dictionary <string, string>()
                {
                    ["email"]     = email,
                    ["password"]  = "******",
                    ["givenName"] = "Galen",
                    ["surname"]   = "Erso",
                    ["codename"]  = "stardust",
                    ["st"]        = csrfToken,
                };

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

                await server.SendAsync(request);

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

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

                // Assert
                account.Should().BeNull();
            }
        }
Esempio n. 15
0
        public async Task SpecifyAccountStore()
        {
            // Arrange
            var directoryName = $"AnotherDirectory {Guid.NewGuid()}";

            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreRegistrationHandler = async(ctx, ct) =>
                    {
                        ctx.AccountStore = await ctx.Client.GetDirectories().Where(d => d.Name == directoryName).SingleAsync();
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

            using (var cleanup = new AutoCleanup(fixture.Client))
            {
                // Create a directory
                var createdDirectory = await fixture.Client.CreateDirectoryAsync(directoryName, $"Test {fixture.TestKey}", DirectoryStatus.Enabled);

                cleanup.MarkForDeletion(createdDirectory);

                var email   = $"its-{fixture.TestKey}@testmail.stormpath.com";
                var payload = new
                {
                    email,
                    password  = "******",
                    givenName = "Cassian",
                    surname   = "Andor"
                };

                var response = await server.PostAsync("/register", new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"));

                response.EnsureSuccessStatusCode();

                var account = await createdDirectory.GetAccounts().Where(a => a.Email == email).SingleAsync();

                account.Should().NotBeNull();
                cleanup.MarkForDeletion(account);
            }
        }
Esempio n. 16
0
        public async Task AccessAccount()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreRegistrationHandler = (ctx, ct) =>
                    {
                        ctx.Account.SetMiddleName("the");
                        return(Task.FromResult(0));
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

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

                // Act
                var email   = $"its-{fixture.TestKey}@testmail.stormpath.com";
                var payload = new
                {
                    email,
                    password  = "******",
                    givenName = "Chewbacca",
                    surname   = "Wookiee"
                };

                var response = await server.PostAsync("/register", new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"));

                response.EnsureSuccessStatusCode();

                var account = await application.GetAccounts().Where(a => a.Email == email).SingleAsync();

                cleanup.MarkForDeletion(account);

                // Assert
                account.FullName.Should().Be("Chewbacca the Wookiee");
            }
        }
Esempio n. 17
0
        public async Task RejectUnknownNestedCustomFieldOnJsonPost()
        {
            // Arrange
            var fixture = new OwinTestFixture();
            var server  = Helpers.CreateServer(fixture);

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

                // Act
                var email = $"its-{fixture.TestKey}@testmail.stormpath.com";
                // Act
                var payload = new
                {
                    email,
                    password   = "******",
                    givenName  = "Galen",
                    surname    = "Erso",
                    customData = new
                    {
                        codename = "stardust"
                    }
                };

                var response = await server.PostAsync(
                    "/register",
                    new StringContent(JsonConvert.SerializeObject(payload),
                                      Encoding.UTF8,
                                      "application/json"));

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

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

                // Assert
                response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
            }
        }
        public async Task AlterLogin()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreLoginHandler = (ctx, ct) =>
                    {
                        ctx.Login = ctx.Login + ".com";
                        return(Task.FromResult(0));
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

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

                var account = await application.CreateAccountAsync(
                    nameof(AlterLogin),
                    nameof(PreLoginHandlerShould),
                    $"its-{fixture.TestKey}@testmail.stormpath.com",
                    "Changeme123!!");

                cleanup.MarkForDeletion(account);

                var payload = new
                {
                    login    = $"its-{fixture.TestKey}@testmail.stormpath", // missing ".com"
                    password = "******"
                };

                // Act
                var response = await server.PostAsync("/login", new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"));

                // Assert
                response.IsSuccessStatusCode.Should().BeTrue();
            }
        }
        public async Task ReturnDefaultErrorMessageDuringFormPost()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreLoginHandler = (ctx, ct) =>
                    {
                        ctx.Result = new PreLoginResult()
                        {
                            Success = false
                        };
                        return(Task.FromResult(0));
                    }
                }
            };
            var server    = Helpers.CreateServer(fixture);
            var csrfToken = await CsrfToken.GetTokenForRoute(server, "/login");

            // Act
            var payload = new Dictionary <string, string>()
            {
                ["login"]    = "******",
                ["password"] = "******",
                ["st"]       = csrfToken,
            };

            var request = new HttpRequestMessage(HttpMethod.Post, "/login")
            {
                Content = new FormUrlEncodedContent(payload)
            };

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));

            var response = await server.SendAsync(request);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.OK);
            (await response.Content.ReadAsStringAsync()).Should().Contain("An error has occurred. Please try again.");
        }
        public async Task ReturnCustomErrorMessageDuringOauthTokenPost()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreLoginHandler = (ctx, ct) =>
                    {
                        ctx.Result = new PreLoginResult()
                        {
                            Success      = false,
                            ErrorMessage = "Nice try, rebel scum!"
                        };
                        return(Task.FromResult(0));
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

            // Act
            var payload = new Dictionary <string, string>()
            {
                ["login"]      = "******",
                ["password"]   = "******",
                ["grant_type"] = "password"
            };

            var request = new HttpRequestMessage(HttpMethod.Post, "/oauth/token")
            {
                Content = new FormUrlEncodedContent(payload)
            };

            var response = await server.SendAsync(request);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
            (await response.Content.ReadAsStringAsync()).Should().Contain("Nice try, rebel scum!");
        }
Esempio n. 21
0
        public async Task RejectRequestsWhenRouteDisabled()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    Configuration = new StormpathConfiguration
                    {
                        Web = new WebConfiguration
                        {
                            Oauth2 = new WebOauth2RouteConfiguration
                            {
                                Enabled = false
                            }
                        }
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

            var payload = new Dictionary <string, string>()
            {
                ["grant_type"] = "notARealRequest",
            };

            // Act
            var request = new HttpRequestMessage(HttpMethod.Post, "/oauth/token")
            {
                Content = new FormUrlEncodedContent(payload)
            };

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = await server.SendAsync(request);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.NotFound);
        }
Esempio n. 22
0
        public async Task AccessPostDataDuringJsonPostWithCustomDataSubobject()
        {
            var handlerRun = false;

            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreRegistrationHandler = (ctx, ct) =>
                    {
                        handlerRun = true;
                        ctx.PostData["email"].Should().Be("*****@*****.**");
                        ctx.PostData["custom"].Should().Be("foobar!");

                        // Don't actually create an account
                        ctx.Result = new PreRegistrationResult
                        {
                            Success = false
                        };

                        return(Task.FromResult(0));
                    },
                    Configuration = new StormpathConfiguration()
                    {
                        Web = new WebConfiguration()
                        {
                            Register = new WebRegisterRouteConfiguration()
                            {
                                Form = new WebRegisterRouteFormConfiguration()
                                {
                                    Fields = new Dictionary <string, WebFieldConfiguration>()
                                    {
                                        ["custom"] = new WebFieldConfiguration()
                                        {
                                            Required    = true,
                                            Enabled     = true,
                                            Label       = "custom",
                                            Placeholder = "custom",
                                            Type        = "text",
                                            Visible     = true
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
            };
            var server = Helpers.CreateServer(fixture);

            // Act
            var payload = new
            {
                email      = "*****@*****.**",
                password   = "******",
                givenName  = "Chewbacca",
                surname    = "Wookiee",
                customData = new
                {
                    custom = "foobar!"
                }
            };

            await server.PostAsync("/register", new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"));

            handlerRun.Should().BeTrue();
        }
Esempio n. 23
0
        public async Task AccessPostDataDuringFormPost()
        {
            var handlerRun = false;

            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreRegistrationHandler = (ctx, ct) =>
                    {
                        handlerRun = true;
                        ctx.PostData["email"].Should().Be("*****@*****.**");
                        ctx.PostData["custom"].Should().Be("foobar!");

                        // Don't actually create an account
                        ctx.Result = new PreRegistrationResult
                        {
                            Success = false
                        };

                        return(Task.FromResult(0));
                    },
                    Configuration = new StormpathConfiguration()
                    {
                        Web = new WebConfiguration()
                        {
                            Register = new WebRegisterRouteConfiguration()
                            {
                                Form = new WebRegisterRouteFormConfiguration()
                                {
                                    Fields = new Dictionary <string, WebFieldConfiguration>()
                                    {
                                        ["custom"] = new WebFieldConfiguration()
                                        {
                                            Required    = true,
                                            Enabled     = true,
                                            Label       = "custom",
                                            Placeholder = "custom",
                                            Type        = "text",
                                            Visible     = true
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
            };
            var server    = Helpers.CreateServer(fixture);
            var csrfToken = await CsrfToken.GetTokenForRoute(server, "/register");

            // Act
            var payload = new Dictionary <string, string>()
            {
                ["email"]     = "*****@*****.**",
                ["password"]  = "******",
                ["givenName"] = "Chewbacca",
                ["surname"]   = "Wookie",
                ["custom"]    = "foobar!",
                ["st"]        = csrfToken,
            };

            var request = new HttpRequestMessage(HttpMethod.Post, "/register")
            {
                Content = new FormUrlEncodedContent(payload)
            };

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));

            await server.SendAsync(request);

            handlerRun.Should().BeTrue();
        }
Esempio n. 24
0
 public static HttpClient CreateServer(OwinTestFixture fixture)
 {
     return(new TestServer(new WebHostBuilder().Configure(fixture.Configure)).CreateClient());
 }
Esempio n. 25
0
        public async Task AcceptCustomFieldsOnFormPost()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    Configuration = new StormpathConfiguration()
                    {
                        Web = new WebConfiguration()
                        {
                            Register = new WebRegisterRouteConfiguration()
                            {
                                Form = new WebRegisterRouteFormConfiguration()
                                {
                                    Fields = new Dictionary <string, WebFieldConfiguration>()
                                    {
                                        ["codename"] = new WebFieldConfiguration()
                                        {
                                            Required    = true,
                                            Enabled     = true,
                                            Label       = "custom",
                                            Placeholder = "custom",
                                            Type        = "text",
                                            Visible     = true
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
            };
            var server    = Helpers.CreateServer(fixture);
            var csrfToken = await CsrfToken.GetTokenForRoute(server, "/register");

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

                // Act
                var email = $"its-{fixture.TestKey}@testmail.stormpath.com";
                // Act
                var payload = new Dictionary <string, string>()
                {
                    ["email"]     = email,
                    ["password"]  = "******",
                    ["givenName"] = "Galen",
                    ["surname"]   = "Erso",
                    ["codename"]  = "stardust",
                    ["st"]        = csrfToken,
                };

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

                await server.SendAsync(request);

                var account = await application.GetAccounts().Where(a => a.Email == email).SingleAsync();

                cleanup.MarkForDeletion(account);

                var customData = await account.GetCustomDataAsync();

                // Assert
                customData["codename"].ToString().Should().Be("stardust");
            }
        }
Esempio n. 26
0
        public async Task AcceptNestedCustomFieldsOnJsonPost()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    Configuration = new StormpathConfiguration()
                    {
                        Web = new WebConfiguration()
                        {
                            Register = new WebRegisterRouteConfiguration()
                            {
                                Form = new WebRegisterRouteFormConfiguration()
                                {
                                    Fields = new Dictionary <string, WebFieldConfiguration>()
                                    {
                                        ["codename"] = new WebFieldConfiguration()
                                        {
                                            Required    = true,
                                            Enabled     = true,
                                            Label       = "custom",
                                            Placeholder = "custom",
                                            Type        = "text",
                                            Visible     = true
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
            };
            var server = Helpers.CreateServer(fixture);

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

                // Act
                var email = $"its-{fixture.TestKey}@testmail.stormpath.com";
                // Act
                var payload = new
                {
                    email,
                    password   = "******",
                    givenName  = "Galen",
                    surname    = "Erso",
                    customData = new
                    {
                        codename = "stardust"
                    }
                };

                var response = await server.PostAsync("/register", new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"));

                response.EnsureSuccessStatusCode();

                var account = await application.GetAccounts().Where(a => a.Email == email).SingleAsync();

                cleanup.MarkForDeletion(account);

                var customData = await account.GetCustomDataAsync();

                // Assert
                customData["codename"].ToString().Should().Be("stardust");
            }
        }
Esempio n. 27
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="));
            }
        }
        public async Task SpecifyOrganizationByNameKey()
        {
            // Arrange
            var fixture = new OwinTestFixture
            {
                Options = new StormpathOwinOptions
                {
                    PreLoginHandler = (ctx, ct) =>
                    {
                        ctx.OrganizationNameKey = "TestOrg";
                        return(Task.CompletedTask);
                    }
                }
            };
            var server = Helpers.CreateServer(fixture);

            using (var cleanup = new AutoCleanup(fixture.Client))
            {
                // Create an organization
                var org = fixture.Client.Instantiate <IOrganization>()
                          .SetName($"Test Organization {fixture.TestKey}")
                          .SetNameKey("TestOrg");
                await fixture.Client.CreateOrganizationAsync(org, opt => opt.CreateDirectory = true);

                cleanup.MarkForDeletion(org);

                var createdDirectory = await fixture.Client.GetDirectories().Where(dir => dir.Name.StartsWith($"Test Organization {fixture.TestKey}")).SingleAsync();

                //cleanup.MarkForDeletion(directory); // TODO

                // Create an account in the organization
                await org.CreateAccountAsync(
                    nameof(SpecifyOrganizationByNameKey),
                    nameof(PreLoginHandlerShould),
                    $"its-{fixture.TestKey}@testmail.stormpath.com",
                    "Changeme123!!");

                // Account will be deleted along with directory

                // Associate the org with our application
                var application = await fixture.Client.GetApplicationAsync(fixture.ApplicationHref);

                await application.AddAccountStoreAsync(org);

                var payload = new Dictionary <string, string>()
                {
                    ["grant_type"] = "password",
                    ["username"]   = $"its-{fixture.TestKey}@testmail.stormpath.com",
                    ["password"]   = "******"
                };

                // Act
                var response = await server.PostAsync("/oauth/token", new FormUrlEncodedContent(payload));

                // Assert
                response.IsSuccessStatusCode.Should().BeTrue();
                var deserializedResponse = JsonConvert.DeserializeObject <Dictionary <string, string> >(await response.Content.ReadAsStringAsync());
                var accessToken          = deserializedResponse["access_token"];

                var body = accessToken.Split('.')[1];
                body = EnsurePadding(body);

                var decodedJwt         = Encoding.UTF8.GetString(Convert.FromBase64String(body));
                var deserializedClaims = JsonConvert.DeserializeObject <Dictionary <string, string> >(decodedJwt);
                deserializedClaims.Should().ContainKey("org");
                deserializedClaims["org"].Should().Be(org.Href);
            }
        }