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 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 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));
        }
Example #4
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 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);
        }
        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);
        }
        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);
            }
        }