Exemple #1
0
        private async Task <IHttpActionResult> RefreshGrantRequest(string refresh_token, IApplication application, CancellationToken cancellationToken)
        {
            // Build and send a request to the Stormpath API
            var refreshGrantRequest = OauthRequests.NewRefreshGrantRequest()
                                      .SetRefreshToken(refresh_token)
                                      .Build();

            try
            {
                var result = await application.NewRefreshGrantAuthenticator()
                             .AuthenticateAsync(refreshGrantRequest, 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 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);
        }
Exemple #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));
        }
        public Task <IOauthGrantAuthenticationResult> ExchangeAsync(IAccount account, CancellationToken cancellationToken)
        {
            var oauthExchangeJwt = _client.NewJwtBuilder()
                                   .SetSubject(account.Href)
                                   .SetIssuedAt(DateTimeOffset.UtcNow.AddSeconds(-5))
                                   .SetExpiration(DateTimeOffset.UtcNow.AddMinutes(1)) // very short
                                   .SetIssuer(_application.Href)
                                   .SetClaim("status", "AUTHENTICATED")
                                   .SetAudience(_configuration.Client.ApiKey.Id)
                                   .SignWith(_configuration.Client.ApiKey.Secret, Encoding.UTF8)
                                   .Build();

            var exchangeRequest = OauthRequests.NewIdSiteTokenAuthenticationRequest()
                                  .SetJwt(oauthExchangeJwt.ToString())
                                  .Build();

            try
            {
                return(_application
                       .NewIdSiteTokenAuthenticator()
                       .AuthenticateAsync(exchangeRequest, cancellationToken));
            }
            catch (ResourceException rex)
            {
                _logger.Warn(rex, source: nameof(StormpathTokenExchanger));

                return(Task.FromResult <IOauthGrantAuthenticationResult>(null));
            }
        }
        public override ClaimsPrincipal ValidateToken(string securityToken,
                                                      TokenValidationParameters validationParameters,
                                                      out SecurityToken validatedToken)
        {
            var jwtAuthenticationRequest = OauthRequests.NewJwtAuthenticationRequest()
                                           .SetJwt(securityToken)
                                           .Build();

            IAccessToken validAccessToken = _stormPathApplication.NewJwtAuthenticator()
                                            .WithLocalValidation()
                                            .AuthenticateAsync(jwtAuthenticationRequest).Result;

            if (validAccessToken == null)
            {
                throw new SecurityTokenException("Invalid token");
            }

            var account = validAccessToken.GetAccountAsync().Result;

            ClaimsIdentity objClaim = new ClaimsIdentity("jwt");

            objClaim.AddClaim(new Claim(ClaimTypes.NameIdentifier, account.Username));
            //Use Email for Name instead FullName
            objClaim.AddClaim(new Claim(ClaimTypes.Name, account.Email));
            objClaim.AddClaim(new Claim(ClaimTypes.Email, account.Email));
            objClaim.AddClaim(new Claim(ClaimTypes.Role, "user"));

            validatedToken = ReadToken(validAccessToken.Jwt);
            var principal = new ClaimsPrincipal(objClaim);

            return(principal);
        }
        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);
        }
Exemple #7
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);
        }
        private async Task <IAccount> RefreshAccessTokenAsync(IOwinEnvironment context, IClient client, string refreshTokenJwt)
        {
            // Attempt refresh grant against Stormpath
            var request = OauthRequests.NewRefreshGrantRequest()
                          .SetRefreshToken(refreshTokenJwt)
                          .Build();

            var application = await client.GetApplicationAsync(this.Configuration.Application.Href, context.CancellationToken);

            var authenticator = application.NewRefreshGrantAuthenticator();

            IOauthGrantAuthenticationResult grantResult = null;

            try
            {
                grantResult = await authenticator.AuthenticateAsync(request, context.CancellationToken);
            }
            catch (InvalidJwtException jwex)
            {
                logger.Info($"Failed to authenticate the request due to a malformed or expired refresh token. Message: '{jwex.Message}'", nameof(RefreshAccessTokenAsync));
                return(null);
            }
            catch (ResourceException rex)
            {
                logger.Warn(rex, "Failed to refresh an access_token given a refresh_token.");
                return(null);
            }

            // Get a new access token
            IAccessToken newAccessToken = null;

            try
            {
                newAccessToken = await grantResult.GetAccessTokenAsync(context.CancellationToken);
            }
            catch (ResourceException rex)
            {
                logger.Error(rex, "Failed to get a new access token after receiving grant response.", nameof(RefreshAccessTokenAsync));
            }

            // Get the account details
            IAccount account = null;

            try
            {
                account = await GetExpandedAccountAsync(client, newAccessToken, context.CancellationToken);
            }
            catch (ResourceException rex)
            {
                logger.Error(rex, $"Failed to get account {newAccessToken.AccountHref}", nameof(RefreshAccessTokenAsync));
                return(null);
            }

            logger.Trace("Access token refreshed using Refresh token. Adding cookies to response", nameof(RefreshAccessTokenAsync));
            Cookies.AddTokenCookiesToResponse(context, client, grantResult, this.Configuration, logger);

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

            return(TestApplication.NewPasswordGrantAuthenticator()
                   .AuthenticateAsync(grantRequest));
        }
        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            HttpRequestMessage        request       = context.Request;
            AuthenticationHeaderValue authorization = request.Headers.Authorization;
            var token = authorization.Parameter;

            if (string.IsNullOrEmpty(token))
            {
                return;
            }


            // Get the Stormpath application
            var application = await StormpathConfig.Client.GetApplicationAsync(StormpathConfig.ApplicationHref);

            // Build and send a request to the Stormpath API
            var jwtValidationRequest = OauthRequests.NewJwtAuthenticationRequest()
                                       .SetJwt(token)
                                       .Build();

            try {
                var validationResult = await application.NewJwtAuthenticator()
                                       .AuthenticateAsync(jwtValidationRequest, cancellationToken);

                var accountDetails = await validationResult.GetAccountAsync();

                // get account -> groups
                var accountGroups = await accountDetails
                                    .GetGroups()
                                    .Expand(g => g.GetCustomData())
                                    .ToListAsync();

                var role = accountGroups.First().Name;

                // Build an IPrincipal and return it
                var claims = new List <Claim>();
                var id     = accountDetails.Href.Split(new char[] { '/' }).Last();
                claims.Add(new Claim(ClaimTypes.PrimarySid, id));
                claims.Add(new Claim(ClaimTypes.Role, role));
                claims.Add(new Claim(ClaimTypes.Email, accountDetails.Email));
                claims.Add(new Claim(ClaimTypes.GivenName, accountDetails.GivenName));
                claims.Add(new Claim(ClaimTypes.Surname, accountDetails.Surname));
                claims.Add(new Claim(ClaimTypes.NameIdentifier, accountDetails.Username));
                var identity = new ClaimsIdentity(claims, AuthenticationTypes.Signature);
                context.Principal = new ClaimsPrincipal(identity);
            }
            catch (ResourceException rex) {
                //// use this code to return the specific error code from StormPath API
                context.ErrorResult = new AuthenticationFailureResult(rex.Message, request);
                return;
            }
        }
        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);
        }
Exemple #13
0
        private async Task <bool> ExecuteRefreshFlow(IOwinEnvironment context, IClient client, string refreshToken, CancellationToken cancellationToken)
        {
            var application = await client.GetApplicationAsync(_configuration.Application.Href, cancellationToken);

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

            var tokenResult = await application.NewRefreshGrantAuthenticator()
                              .AuthenticateAsync(refreshGrantRequest, cancellationToken);

            var sanitizer = new GrantResultResponseSanitizer();

            return(await JsonResponse.Ok(context, sanitizer.SanitizeResponseWithRefreshToken(tokenResult)).ConfigureAwait(false));
        }
        public async Task Validating_ID_site_token_fails()
        {
            var fakeDataStore   = GetFakeDataStore();
            var fakeApplication = await fakeDataStore.GetResourceAsync <IApplication>("https://api.stormpath.com/v1/applications/foobarApplication");

            var request = OauthRequests.NewJwtAuthenticationRequest()
                          .SetJwt(IDSiteAccessToken)
                          .Build();

            IJwtAuthenticator authenticator = new DefaultJwtAuthenticator(fakeApplication, fakeDataStore);

            authenticator.WithLocalValidation();

            await Should.ThrowAsync <MismatchedClaimException>(authenticator.AuthenticateAsync(request));
        }
        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);
        }
Exemple #16
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);
        }
Exemple #17
0
        public static async Task <bool> ValidateAccessToken()
        {
            try {
                var    app          = StormpathConfig.Application;
                string access_token = AccessToken;

                var validationRequest = OauthRequests.NewJwtAuthenticationRequest()
                                        .SetJwt(access_token)
                                        .Build();

                var accessToken = await app.NewJwtAuthenticator()
                                  .AuthenticateAsync(validationRequest);

                return(true);
            }
            catch { return(false); }
        }
        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);
        }
        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);
        }
        private async Task <IAccount> ValidateAccessTokenAsync(IOwinEnvironment context, IClient client, string accessTokenJwt)
        {
            var request = OauthRequests.NewJwtAuthenticationRequest()
                          .SetJwt(accessTokenJwt)
                          .Build();

            var application = await client.GetApplicationAsync(this.Configuration.Application.Href, context.CancellationToken);

            var authenticator = application.NewJwtAuthenticator();

            if (this.Configuration.Web.Oauth2.Password.ValidationStrategy == WebOauth2TokenValidationStrategy.Local)
            {
                authenticator.WithLocalValidation();
            }

            IAccessToken result = null;

            try
            {
                result = await authenticator.AuthenticateAsync(request, context.CancellationToken);
            }
            catch (InvalidJwtException jwex)
            {
                logger.Info($"Failed to authenticate the request due to a malformed or expired access token. Message: '{jwex.Message}'", nameof(ValidateAccessTokenAsync));
                return(null);
            }
            catch (ResourceException rex)
            {
                logger.Warn(rex, "Failed to authenticate the request. Invalid access_token found.", nameof(ValidateAccessTokenAsync));
                return(null);
            }

            IAccount account = null;

            try
            {
                account = await GetExpandedAccountAsync(client, result, context.CancellationToken);
            }
            catch (ResourceException ex)
            {
                logger.Error(ex, $"Failed to get account {result.AccountHref}", nameof(ValidateAccessTokenAsync));
            }

            return(account);
        }
        private async Task <IOauthGrantAuthenticationResult> ExchangeTokenAsync(IApplication application, IJwt jwt, CancellationToken cancellationToken)
        {
            try
            {
                var tokenExchangeAttempt = OauthRequests.NewIdSiteTokenAuthenticationRequest()
                                           .SetJwt(jwt.ToString())
                                           .Build();

                var grantResult = await application.NewIdSiteTokenAuthenticator()
                                  .AuthenticateAsync(tokenExchangeAttempt, cancellationToken);

                return(grantResult);
            }
            catch (ResourceException rex)
            {
                _logger.Warn(rex, source: nameof(ExchangeTokenAsync));
                throw; // json response
            }
        }
        public async Task Validating_token_with_specified_issuer()
        {
            var fakeDataStore   = GetFakeDataStore();
            var fakeApplication = await fakeDataStore.GetResourceAsync <IApplication>("https://api.stormpath.com/v1/applications/foobarApplication");

            var request = OauthRequests.NewJwtAuthenticationRequest()
                          .SetJwt(IDSiteAccessToken)
                          .Build();

            IJwtAuthenticator authenticator = new DefaultJwtAuthenticator(fakeApplication, fakeDataStore);

            authenticator.WithLocalValidation(new JwtLocalValidationOptions()
            {
                Issuer = "https://awesome-tenant.id.stormpath.io"
            });

            // Should not throw
            var result = await authenticator.AuthenticateAsync(request);

            result.Jwt.ShouldBe(IDSiteAccessToken);
        }
Exemple #23
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);
        }
        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);
        }
        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);
        }
        protected override async Task <IPrincipal> AuthenticateAsync(string token, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(token))
            {
                return(null);
            }

            // Get the Stormpath application
            var application = await StormpathConfig.Client.GetApplicationAsync(StormpathConfig.ApplicationHref);

            // Build and send a request to the Stormpath API
            var jwtValidationRequest = OauthRequests.NewJwtAuthenticationRequest()
                                       .SetJwt(token)
                                       .Build();

            try
            {
                var validationResult = await application.NewJwtAuthenticator()
                                       .AuthenticateAsync(jwtValidationRequest, cancellationToken);

                var accountDetails = await validationResult.GetAccountAsync();

                // Build an IPrincipal and return it
                var claims = new List <Claim>();
                claims.Add(new Claim(ClaimTypes.Email, accountDetails.Email));
                claims.Add(new Claim(ClaimTypes.GivenName, accountDetails.GivenName));
                claims.Add(new Claim(ClaimTypes.Surname, accountDetails.Surname));
                claims.Add(new Claim(ClaimTypes.NameIdentifier, accountDetails.Username));
                var identity = new ClaimsIdentity(claims, AuthenticationTypes.Signature);
                return(new ClaimsPrincipal(identity));
            }
            catch (ResourceException rex)
            {
                return(null);
            }
        }