Ejemplo n.º 1
0
        public void Failed_password_grant_throws_ResourceException(TestClientProvider clientBuilder)
        {
            var client = clientBuilder.GetClient();
            var tenant = client.GetCurrentTenant();

            // Create a dummy application
            var createdApplication = tenant.CreateApplication(
                $".NET IT {this.fixture.TestRunIdentifier}-{clientBuilder.Name} Failed Password Grant Throws - Sync",
                createDirectory: false);

            createdApplication.Href.ShouldNotBeNullOrEmpty();
            this.fixture.CreatedApplicationHrefs.Add(createdApplication.Href);

            // Add the test accounts
            createdApplication.AddAccountStore(this.fixture.PrimaryDirectoryHref);

            var badPasswordGrantRequest = OauthRequests.NewPasswordGrantRequest()
                                          .SetLogin("*****@*****.**")
                                          .SetPassword("notLukesPassword")
                                          .Build();

            // TODO Mono Shouldly support - should be ResourceException
            Should.Throw <Exception>(() => createdApplication.NewPasswordGrantAuthenticator().Authenticate(badPasswordGrantRequest));

            createdApplication.Delete().ShouldBeTrue();
            this.fixture.CreatedApplicationHrefs.Remove(createdApplication.Href);
        }
Ejemplo n.º 2
0
        public async Task Failed_password_grant_throws_ResourceException(TestClientProvider clientBuilder)
        {
            var client = clientBuilder.GetClient();
            var tenant = await client.GetCurrentTenantAsync();

            // Create a dummy application
            var createdApplication = await tenant.CreateApplicationAsync(
                $".NET IT {this.fixture.TestRunIdentifier}-{clientBuilder.Name} Failed Password Grant Throws",
                createDirectory : false);

            createdApplication.Href.ShouldNotBeNullOrEmpty();
            this.fixture.CreatedApplicationHrefs.Add(createdApplication.Href);

            // Add the test accounts
            await createdApplication.AddAccountStoreAsync(this.fixture.PrimaryDirectoryHref);

            var badPasswordGrantRequest = OauthRequests.NewPasswordGrantRequest()
                                          .SetLogin("*****@*****.**")
                                          .SetPassword("notLukesPassword")
                                          .Build();

            await Should.ThrowAsync <ResourceException>(async() => await createdApplication.NewPasswordGrantAuthenticator().AuthenticateAsync(badPasswordGrantRequest));

            (await createdApplication.DeleteAsync()).ShouldBeTrue();
            this.fixture.CreatedApplicationHrefs.Remove(createdApplication.Href);
        }
Ejemplo n.º 3
0
        private async Task <bool> ExecutePasswordFlow(IOwinEnvironment context, IClient client, string username, string password, CancellationToken cancellationToken)
        {
            var preLoginContext = new PreLoginContext(context)
            {
                Login = username
            };
            await _handlers.PreLoginHandler(preLoginContext, cancellationToken);

            var passwordGrantRequestBuilder = OauthRequests.NewPasswordGrantRequest()
                                              .SetLogin(preLoginContext.Login)
                                              .SetPassword(password);

            if (preLoginContext.AccountStore != null)
            {
                passwordGrantRequestBuilder.SetAccountStore(preLoginContext.AccountStore);
            }

            var passwordGrantRequest = passwordGrantRequestBuilder.Build();

            var application = await client.GetApplicationAsync(_configuration.Application.Href, cancellationToken);

            var tokenResult = await application.NewPasswordGrantAuthenticator()
                              .AuthenticateAsync(passwordGrantRequest, cancellationToken);

            var accessToken = await tokenResult.GetAccessTokenAsync(cancellationToken);

            var account = await accessToken.GetAccountAsync(cancellationToken);

            var postLoginContext = new PostLoginContext(context, account);
            await _handlers.PostLoginHandler(postLoginContext, cancellationToken);

            var sanitizer = new GrantResultResponseSanitizer();

            return(await JsonResponse.Ok(context, sanitizer.SanitizeResponseWithRefreshToken(tokenResult)).ConfigureAwait(false));
        }
Ejemplo n.º 4
0
        private async Task <IHttpActionResult> PasswordGrantRequest(string username, string password, IApplication application, CancellationToken cancellationToken)
        {
            // Build and send a request to the Stormpath API
            var passwordGrantRequest = OauthRequests.NewPasswordGrantRequest()
                                       .SetLogin(username)
                                       .SetPassword(password)
                                       .Build();

            try
            {
                var result = await application.NewPasswordGrantAuthenticator()
                             .AuthenticateAsync(passwordGrantRequest, cancellationToken);

                return(Ok(new TokenResult()
                {
                    AccessToken = result.AccessTokenString,
                    RefreshToken = result.RefreshTokenString,
                    TokenType = result.TokenType,
                    ExpiresIn = result.ExpiresIn
                }));
            }
            catch (ResourceException rex)
            {
                return(BadRequest(rex.Message));
            }
        }
        public async Task <IOauthGrantAuthenticationResult> PasswordGrantAsync(
            IOwinEnvironment environment,
            IApplication application,
            string login,
            string password,
            CancellationToken cancellationToken)
        {
            var preLoginHandlerContext = new PreLoginContext(environment)
            {
                Login = login
            };

            await _handlers.PreLoginHandler(preLoginHandlerContext, cancellationToken);

            var passwordGrantRequest = OauthRequests.NewPasswordGrantRequest()
                                       .SetLogin(preLoginHandlerContext.Login)
                                       .SetPassword(password);

            if (preLoginHandlerContext.AccountStore != null)
            {
                passwordGrantRequest.SetAccountStore(preLoginHandlerContext.AccountStore);
            }

            var passwordGrantAuthenticator = application.NewPasswordGrantAuthenticator();
            var grantResult = await passwordGrantAuthenticator
                              .AuthenticateAsync(passwordGrantRequest.Build(), cancellationToken);

            return(grantResult);
        }
        public Task <IOauthGrantAuthenticationResult> GetGrantResult(IAccount account, string password)
        {
            var grantRequest = OauthRequests.NewPasswordGrantRequest()
                               .SetLogin(account.Email)
                               .SetPassword(password)
                               .Build();

            return(TestApplication.NewPasswordGrantAuthenticator()
                   .AuthenticateAsync(grantRequest));
        }
Ejemplo n.º 7
0
        public async Task Refreshing_access_token_with_instance(TestClientProvider clientBuilder)
        {
            var client = clientBuilder.GetClient();
            var tenant = await client.GetCurrentTenantAsync();

            // Create a dummy application
            var createdApplication = await tenant.CreateApplicationAsync(
                $".NET IT {this.fixture.TestRunIdentifier}-{clientBuilder.Name} Getting Refresh Token for Application",
                createDirectory : false);

            createdApplication.Href.ShouldNotBeNullOrEmpty();
            this.fixture.CreatedApplicationHrefs.Add(createdApplication.Href);

            // Add the test accounts
            await createdApplication.AddAccountStoreAsync(this.fixture.PrimaryDirectoryHref);

            var passwordGrantRequest = OauthRequests.NewPasswordGrantRequest()
                                       .SetLogin("*****@*****.**")
                                       .SetPassword("whataPieceofjunk$1138")
                                       .SetAccountStore(this.fixture.PrimaryDirectoryHref)
                                       .Build();
            var originalGrantResult = await createdApplication.NewPasswordGrantAuthenticator()
                                      .AuthenticateAsync(passwordGrantRequest);

            var account = await tenant.GetAccountAsync(this.fixture.PrimaryAccountHref);

            var refreshToken = await account
                               .GetRefreshTokens()
                               .Where(x => x.ApplicationHref == createdApplication.Href)
                               .SingleOrDefaultAsync();

            refreshToken.ShouldNotBeNull();

            var refreshGrantRequest = OauthRequests.NewRefreshGrantRequest()
                                      .SetRefreshToken(refreshToken)
                                      .Build();

            var refreshGrantResult = await createdApplication.NewRefreshGrantAuthenticator()
                                     .AuthenticateAsync(refreshGrantRequest);

            refreshGrantResult.AccessTokenHref.ShouldNotBe(originalGrantResult.AccessTokenHref);
            refreshGrantResult.AccessTokenString.ShouldNotBe(originalGrantResult.AccessTokenString);
            refreshGrantResult.RefreshTokenString.ShouldBe(originalGrantResult.RefreshTokenString);

            // Clean up
            (await refreshToken.DeleteAsync()).ShouldBeTrue();

            (await createdApplication.DeleteAsync()).ShouldBeTrue();
            this.fixture.CreatedApplicationHrefs.Remove(createdApplication.Href);
        }
        public async Task <string> Login(LoginModel loginValues)
        {
            var passwordGrantRequest = OauthRequests.NewPasswordGrantRequest()
                                       .SetLogin(loginValues.UserName)
                                       .SetPassword(loginValues.Password)
                                       .Build();

            var grantResult = await _stormpathApplication.NewPasswordGrantAuthenticator()
                              .AuthenticateAsync(passwordGrantRequest);

            var accessToken = await grantResult.GetAccessTokenAsync();

            return(accessToken.Jwt);
        }
        public async Task <IOauthGrantAuthenticationResult> PasswordGrantAsync(
            IOwinEnvironment environment,
            IApplication application,
            Func <string, CancellationToken, Task> errorHandler,
            string login,
            string password,
            CancellationToken cancellationToken)
        {
            var preLoginHandlerContext = new PreLoginContext(environment)
            {
                Login = login
            };

            await _handlers.PreLoginHandler(preLoginHandlerContext, cancellationToken);

            if (preLoginHandlerContext.Result != null)
            {
                if (!preLoginHandlerContext.Result.Success)
                {
                    var message = string.IsNullOrEmpty(preLoginHandlerContext.Result.ErrorMessage)
                        ? "An error has occurred. Please try again."
                        : preLoginHandlerContext.Result.ErrorMessage;
                    await errorHandler(message, cancellationToken);

                    return(null);
                }
            }

            var passwordGrantRequest = OauthRequests.NewPasswordGrantRequest()
                                       .SetLogin(preLoginHandlerContext.Login)
                                       .SetPassword(password);

            if (preLoginHandlerContext.AccountStore != null)
            {
                passwordGrantRequest.SetAccountStore(preLoginHandlerContext.AccountStore);
            }

            if (!string.IsNullOrEmpty(preLoginHandlerContext.OrganizationNameKey))
            {
                passwordGrantRequest.SetOrganizationNameKey(preLoginHandlerContext.OrganizationNameKey);
            }

            var passwordGrantAuthenticator = application.NewPasswordGrantAuthenticator();
            var grantResult = await passwordGrantAuthenticator
                              .AuthenticateAsync(passwordGrantRequest.Build(), cancellationToken);

            return(grantResult);
        }
Ejemplo n.º 10
0
        public void Getting_refresh_token_for_application(TestClientProvider clientBuilder)
        {
            var client = clientBuilder.GetClient();
            var tenant = client.GetCurrentTenant();

            // Create a dummy application
            var createdApplication = tenant.CreateApplication(
                $".NET IT {this.fixture.TestRunIdentifier}-{clientBuilder.Name} Getting Refresh Token for Application - Sync",
                createDirectory: false);

            createdApplication.Href.ShouldNotBeNullOrEmpty();
            this.fixture.CreatedApplicationHrefs.Add(createdApplication.Href);

            // Add the test accounts
            createdApplication.AddAccountStore(this.fixture.PrimaryDirectoryHref);

            var passwordGrantRequest = OauthRequests.NewPasswordGrantRequest()
                                       .SetLogin("*****@*****.**")
                                       .SetPassword("whataPieceofjunk$1138")
                                       .SetAccountStore(this.fixture.PrimaryDirectoryHref)
                                       .Build();
            var authenticateResult = createdApplication.NewPasswordGrantAuthenticator()
                                     .Authenticate(passwordGrantRequest);

            var account = tenant.GetAccount(this.fixture.PrimaryAccountHref);
            var refreshTokenForApplication = account
                                             .GetRefreshTokens()
                                             .Where(x => x.ApplicationHref == createdApplication.Href)
                                             .Synchronously()
                                             .SingleOrDefault();

            refreshTokenForApplication.ShouldNotBeNull();

            refreshTokenForApplication.GetAccount().Href.ShouldBe(this.fixture.PrimaryAccountHref);
            refreshTokenForApplication.GetApplication().Href.ShouldBe(createdApplication.Href);
            refreshTokenForApplication.GetTenant().Href.ShouldBe(this.fixture.TenantHref);

            var retrievedDirectly = client.GetRefreshToken(refreshTokenForApplication.Href);

            retrievedDirectly.Href.ShouldBe(refreshTokenForApplication.Href);

            // Clean up
            refreshTokenForApplication.Delete().ShouldBeTrue();

            createdApplication.Delete().ShouldBeTrue();
            this.fixture.CreatedApplicationHrefs.Remove(createdApplication.Href);
        }
Ejemplo n.º 11
0
        public async Task Creating_token_with_password_grant(TestClientProvider clientBuilder)
        {
            var client = clientBuilder.GetClient();
            var tenant = await client.GetCurrentTenantAsync();

            // Create a dummy application
            var createdApplication = await tenant.CreateApplicationAsync(
                $".NET IT {this.fixture.TestRunIdentifier}-{clientBuilder.Name} Creating Token With Password Grant Flow",
                createDirectory : false);

            createdApplication.Href.ShouldNotBeNullOrEmpty();
            this.fixture.CreatedApplicationHrefs.Add(createdApplication.Href);

            // Add the test accounts
            await createdApplication.AddAccountStoreAsync(this.fixture.PrimaryDirectoryHref);

            var passwordGrantRequest = OauthRequests.NewPasswordGrantRequest()
                                       .SetLogin("*****@*****.**")
                                       .SetPassword("whataPieceofjunk$1138")
                                       .SetAccountStore(this.fixture.PrimaryDirectoryHref)
                                       .Build();
            var authenticateResult = await createdApplication.NewPasswordGrantAuthenticator()
                                     .AuthenticateAsync(passwordGrantRequest);

            // Verify authentication response
            authenticateResult.AccessTokenHref.ShouldContain("/accessTokens/");
            authenticateResult.AccessTokenString.ShouldNotBeNullOrEmpty();
            authenticateResult.ExpiresIn.ShouldBeGreaterThanOrEqualTo(3600);
            authenticateResult.TokenType.ShouldBe("Bearer");
            authenticateResult.RefreshTokenString.ShouldNotBeNullOrEmpty();

            // Verify generated access token
            var accessToken = await authenticateResult.GetAccessTokenAsync();

            accessToken.CreatedAt.ShouldNotBe(default(DateTimeOffset));
            accessToken.Href.ShouldBe(authenticateResult.AccessTokenHref);
            accessToken.Jwt.ShouldBe(authenticateResult.AccessTokenString);
            accessToken.ApplicationHref.ShouldBe(createdApplication.Href);

            // Clean up
            (await accessToken.DeleteAsync()).ShouldBeTrue();

            (await createdApplication.DeleteAsync()).ShouldBeTrue();
            this.fixture.CreatedApplicationHrefs.Remove(createdApplication.Href);
        }
Ejemplo n.º 12
0
        public async Task Validating_jwt_locally(TestClientProvider clientBuilder)
        {
            var client = clientBuilder.GetClient();
            var tenant = await client.GetCurrentTenantAsync();

            // Create a dummy application
            var createdApplication = await tenant.CreateApplicationAsync(
                $".NET IT {this.fixture.TestRunIdentifier}-{clientBuilder.Name} Validating JWT Locally",
                createDirectory : false);

            createdApplication.Href.ShouldNotBeNullOrEmpty();
            this.fixture.CreatedApplicationHrefs.Add(createdApplication.Href);

            // Add the test accounts
            await createdApplication.AddAccountStoreAsync(this.fixture.PrimaryDirectoryHref);

            var passwordGrantRequest = OauthRequests.NewPasswordGrantRequest()
                                       .SetLogin("*****@*****.**")
                                       .SetPassword("whataPieceofjunk$1138")
                                       .SetAccountStore(this.fixture.PrimaryDirectoryHref)
                                       .Build();
            var authenticateResult = await createdApplication.NewPasswordGrantAuthenticator()
                                     .AuthenticateAsync(passwordGrantRequest);

            var accessTokenJwt = authenticateResult.AccessTokenString;

            var jwtAuthenticationRequest = OauthRequests.NewJwtAuthenticationRequest()
                                           .SetJwt(accessTokenJwt)
                                           .Build();
            var validAccessToken = await createdApplication.NewJwtAuthenticator()
                                   .WithLocalValidation()
                                   .AuthenticateAsync(jwtAuthenticationRequest);

            validAccessToken.ShouldNotBeNull();
            validAccessToken.ApplicationHref.ShouldBe(createdApplication.Href);
            validAccessToken.CreatedAt.ShouldBe(DateTimeOffset.Now, Delay.ReasonableTestRunWindow);
            validAccessToken.Href.ShouldBe(authenticateResult.AccessTokenHref);
            validAccessToken.Jwt.ShouldBe(accessTokenJwt);

            // Clean up
            (await validAccessToken.DeleteAsync()).ShouldBeTrue();

            (await createdApplication.DeleteAsync()).ShouldBeTrue();
            this.fixture.CreatedApplicationHrefs.Remove(createdApplication.Href);
        }
Ejemplo n.º 13
0
        public void Refreshing_access_token_with_jwt(TestClientProvider clientBuilder)
        {
            var client = clientBuilder.GetClient();
            var tenant = client.GetCurrentTenant();

            // Create a dummy application
            var createdApplication = tenant.CreateApplication(
                $".NET IT {this.fixture.TestRunIdentifier}-{clientBuilder.Name} Refreshing Access Token - Sync",
                createDirectory: false);

            createdApplication.Href.ShouldNotBeNullOrEmpty();
            this.fixture.CreatedApplicationHrefs.Add(createdApplication.Href);

            // Add the test accounts
            createdApplication.AddAccountStore(this.fixture.PrimaryDirectoryHref);

            var passwordGrantRequest = OauthRequests.NewPasswordGrantRequest()
                                       .SetLogin("*****@*****.**")
                                       .SetPassword("whataPieceofjunk$1138")
                                       .SetAccountStore(this.fixture.PrimaryDirectoryHref)
                                       .Build();
            var originalGrantResult = createdApplication.NewPasswordGrantAuthenticator()
                                      .Authenticate(passwordGrantRequest);

            var refreshGrantRequest = OauthRequests.NewRefreshGrantRequest()
                                      .SetRefreshToken(originalGrantResult.RefreshTokenString)
                                      .Build();

            var refreshGrantResult = createdApplication.NewRefreshGrantAuthenticator()
                                     .Authenticate(refreshGrantRequest);

            refreshGrantResult.AccessTokenHref.ShouldNotBe(originalGrantResult.AccessTokenHref);
            refreshGrantResult.AccessTokenString.ShouldNotBe(originalGrantResult.AccessTokenString);
            refreshGrantResult.RefreshTokenString.ShouldBe(originalGrantResult.RefreshTokenString);

            // Clean up
            createdApplication.Delete().ShouldBeTrue();
            this.fixture.CreatedApplicationHrefs.Remove(createdApplication.Href);
        }
Ejemplo n.º 14
0
        public async Task Validating_token_after_revocation(TestClientProvider clientBuilder)
        {
            var client = clientBuilder.GetClient();
            var tenant = await client.GetCurrentTenantAsync();

            // Create a dummy application
            var createdApplication = await tenant.CreateApplicationAsync(
                $".NET IT {this.fixture.TestRunIdentifier}-{clientBuilder.Name} Validating Token After Revocation",
                createDirectory : false);

            createdApplication.Href.ShouldNotBeNullOrEmpty();
            this.fixture.CreatedApplicationHrefs.Add(createdApplication.Href);

            // Add the test accounts
            await createdApplication.AddAccountStoreAsync(this.fixture.PrimaryDirectoryHref);

            var passwordGrantRequest = OauthRequests.NewPasswordGrantRequest()
                                       .SetLogin("*****@*****.**")
                                       .SetPassword("whataPieceofjunk$1138")
                                       .SetAccountStore(this.fixture.PrimaryDirectoryHref)
                                       .Build();
            var authenticateResult = await createdApplication.NewPasswordGrantAuthenticator()
                                     .AuthenticateAsync(passwordGrantRequest);

            var accessToken = await authenticateResult.GetAccessTokenAsync();

            (await accessToken.DeleteAsync()).ShouldBeTrue(); // Revoke access token

            var jwtAuthenticationRequest = OauthRequests.NewJwtAuthenticationRequest()
                                           .SetJwt(accessToken.Jwt)
                                           .Build();

            await Should.ThrowAsync <ResourceException>(async() => await createdApplication.NewJwtAuthenticator().AuthenticateAsync(jwtAuthenticationRequest));

            // Clean up
            (await createdApplication.DeleteAsync()).ShouldBeTrue();
            this.fixture.CreatedApplicationHrefs.Remove(createdApplication.Href);
        }
Ejemplo n.º 15
0
        public async Task Validating_jwt_locally_throws_for_bad_jwt(TestClientProvider clientBuilder)
        {
            var client = clientBuilder.GetClient();
            var tenant = await client.GetCurrentTenantAsync();

            // Create a dummy application
            var createdApplication = await tenant.CreateApplicationAsync(
                $".NET IT {this.fixture.TestRunIdentifier}-{clientBuilder.Name} Validating JWT Locally",
                createDirectory : false);

            createdApplication.Href.ShouldNotBeNullOrEmpty();
            this.fixture.CreatedApplicationHrefs.Add(createdApplication.Href);

            // Add the test accounts
            await createdApplication.AddAccountStoreAsync(this.fixture.PrimaryDirectoryHref);

            var passwordGrantRequest = OauthRequests.NewPasswordGrantRequest()
                                       .SetLogin("*****@*****.**")
                                       .SetPassword("whataPieceofjunk$1138")
                                       .SetAccountStore(this.fixture.PrimaryDirectoryHref)
                                       .Build();
            var authenticateResult = await createdApplication.NewPasswordGrantAuthenticator()
                                     .AuthenticateAsync(passwordGrantRequest);

            var badJwt = authenticateResult.AccessTokenString
                         .Substring(0, authenticateResult.AccessTokenString.Length - 3) + "foo";

            var jwtAuthenticationRequest = OauthRequests.NewJwtAuthenticationRequest()
                                           .SetJwt(badJwt)
                                           .Build();

            await Should.ThrowAsync <JwtSignatureException>(async() =>
                                                            await createdApplication.NewJwtAuthenticator().WithLocalValidation().AuthenticateAsync(jwtAuthenticationRequest));

            // Clean up
            (await createdApplication.DeleteAsync()).ShouldBeTrue();
            this.fixture.CreatedApplicationHrefs.Remove(createdApplication.Href);
        }