public async Task Name_invalid_secret_should_not_match()
        {
            ISecretValidator validator = new X509NameSecretValidator(new Logger <X509NameSecretValidator>(new LoggerFactory()));

            var clientId = "mtls_client_invalid";
            var client   = await _clients.FindEnabledClientByIdAsync(clientId);

            var secret = new ParsedSecret
            {
                Id         = clientId,
                Credential = TestCert.Load(),
                Type       = IdentityServerConstants.ParsedSecretTypes.X509Certificate
            };

            var result = await validator.ValidateAsync(client.ClientSecrets, secret);

            result.Success.Should().BeFalse();
        }
Ejemplo n.º 2
0
        public async Task authorize_should_accept_valid_JWT_request_without_query_string_parameters()
        {
            var requestJwt = CreateRequestJwt(
                issuer: _client.ClientId,
                audience: IdentityServerPipeline.BaseUrl,
                credential: new X509SigningCredentials(TestCert.Load()),
                claims: new[] {
                new Claim("client_id", _client.ClientId),
                new Claim("response_type", "id_token"),
                new Claim("scope", "openid profile"),
                new Claim("state", "123state"),
                new Claim("nonce", "123nonce"),
                new Claim("redirect_uri", "https://client/callback"),
                new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"),
                new Claim("login_hint", "login_hint_value"),
                new Claim("display", "popup"),
                new Claim("ui_locales", "ui_locale_value"),
                new Claim("foo", "123foo"),
            });

            var url = _mockPipeline.CreateAuthorizeUrl(
                extra: new
            {
                request = requestJwt
            });
            var response = await _mockPipeline.BrowserClient.GetAsync(url);

            _mockPipeline.LoginRequest.Should().NotBeNull();
            _mockPipeline.LoginRequest.ClientId.Should().Be(_client.ClientId);
            _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup");
            _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value");
            _mockPipeline.LoginRequest.IdP.Should().Be("idp_value");
            _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value");
            _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value");
            _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" });

            _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo");
            _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo");

            _mockPipeline.LoginRequest.RequestObjectValues.Count.Should().Be(11);
            _mockPipeline.LoginRequest.RequestObjectValues.Should().ContainKey("foo");
            _mockPipeline.LoginRequest.RequestObjectValues["foo"].Should().Be("123foo");
        }
Ejemplo n.º 3
0
    public static TokenValidator CreateTokenValidator(
        IReferenceTokenStore store           = null,
        IRefreshTokenStore refreshTokenStore = null,
        IProfileService profile = null,
        IIssuerNameService issuerNameService = null,
        IdentityServerOptions options        = null,
        ISystemClock clock = null)
    {
        options ??= TestIdentityServerOptions.Create();
        profile ??= new TestProfileService();
        store ??= CreateReferenceTokenStore();
        clock ??= new StubClock();
        refreshTokenStore ??= CreateRefreshTokenStore();
        issuerNameService ??= new TestIssuerNameService(options.IssuerUri);

        var clients = CreateClientStore();

        var logger = TestLogger.Create <TokenValidator>();

        var keyInfo = new SecurityKeyInfo
        {
            Key = TestCert.LoadSigningCredentials().Key,
            SigningAlgorithm = "RS256"
        };

        var validator = new TokenValidator(
            clients: clients,
            clock: clock,
            profile: profile,
            referenceTokenStore: store,
            customValidator: new DefaultCustomTokenValidator(),
            keys: new DefaultKeyMaterialService(
                new[] { new InMemoryValidationKeysStore(new[] { keyInfo }) },
                Enumerable.Empty <ISigningCredentialStore>(),
                new NopAutomaticKeyManagerKeyStore()
                ),
            sessionCoordinationService: new StubSessionCoordinationService(),
            logger: logger,
            options: options,
            issuerNameService: issuerNameService);

        return(validator);
    }
        public async Task authorize_should_ignore_request_uri_when_feature_is_disabled()
        {
            _mockPipeline.Options.Endpoints.EnableJwtRequestUri = false;

            var requestJwt = CreateRequestJwt(
                issuer: _client.ClientId,
                audience: IdentityServerPipeline.BaseUrl,
                credential: new X509SigningCredentials(TestCert.Load()),
                claims: new[] {
                new Claim("client_id", _client.ClientId),
                new Claim("response_type", "id_token"),
                new Claim("scope", "openid profile"),
                new Claim("state", "123state"),
                new Claim("nonce", "123nonce"),
                new Claim("redirect_uri", "https://client/callback"),
                new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"),
                new Claim("login_hint", "login_hint_value"),
                new Claim("display", "popup"),
                new Claim("ui_locales", "ui_locale_value"),
                new Claim("foo", "123foo"),
            });

            _mockPipeline.JwtRequestMessageHandler.OnInvoke = req =>
            {
                req.RequestUri.Should().Be(new Uri("http://client_jwt"));
                return(Task.CompletedTask);
            };
            _mockPipeline.JwtRequestMessageHandler.Response.Content = new StringContent(requestJwt);


            var url = _mockPipeline.CreateAuthorizeUrl(
                clientId: _client.ClientId,
                responseType: "id_token",
                extra: new
            {
                request_uri = "http://client_jwt"
            });
            var response = await _mockPipeline.BrowserClient.GetAsync(url);

            _mockPipeline.ErrorWasCalled.Should().BeTrue();

            _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeFalse();
        }
Ejemplo n.º 5
0
        public async Task CertificateAndClientIdPresent()
        {
            var parser  = new X509CertificateSecretParser();
            var context = new OwinContext();

            var body = "client_id=client";

            context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));

            var cert = TestCert.Load();

            context.Set("ssl.ClientCertificate", cert);

            var secret = await parser.ParseAsync(context.Environment);

            secret.Type.Should().Be(Constants.ParsedSecretTypes.X509Certificate);
            secret.Id.Should().Be("client");
            secret.Credential.Should().NotBeNull();
            secret.Credential.Should().BeEquivalentTo(cert);
        }
Ejemplo n.º 6
0
        public static AppBuilder Create()
        {
            AppBuilder app = new AppBuilder();

            var factory = new IdentityServerServiceFactory()
                          .UseInMemoryClients(Clients.Get())
                          .UseInMemoryScopes(Scopes.Get())
                          .UseInMemoryUsers(Users.Get());

            factory.CustomGrantValidators.Add(new Registration <ICustomGrantValidator, CustomGrantValidator>());
            factory.CustomGrantValidators.Add(new Registration <ICustomGrantValidator, CustomGrantValidator2>());

            app.UseIdentityServer(new IdentityServerOptions
            {
                IssuerUri          = "https://idsrv3",
                SigningCertificate = TestCert.Load(),

                Factory = factory
            });

            return(app);
        }
Ejemplo n.º 7
0
 public static void GetDatiExt(List <Dati> ListaDati, bool EsclCestino)
 {
     //Importa i dati che non sono programmi e sono fissi
     importDati.GetDatiKit('K', ListaDati);
     importDati.GetDatiPatchSO('B', ListaDati);
     importDati.GetDatiPatchOffice('B', ListaDati);
     importDati.GetDatiPatchCA('B', ListaDati);
     importDati.GetDatiAVEngine('V', ListaDati);
     importDati.GetDatiUtentiDir('U', ListaDati);
     //
     //Alimentazione
     TestPwrMng.GetPwr('A', ListaDati);
     //Altro Registro e Servizi
     if (TestCfgSrvs != null)
     {
         TestServizi.GetSrv(TestCfgSrvs, ListaDati);
     }
     if (TestCfgRegs != null)
     {
         TestRegistri.GetReg(TestCfgRegs, ListaDati);
     }
     if (TestCfgCrts != null)
     {
         TestCert.GetSrv(TestCfgCrts, ListaDati);
     }
     if (TestCfgFiles != null)
     {
         TestFile.GetFileEx(TestCfgFiles, ListaDati);
     }
     if (TestCfgWMIQ != null)
     {
         TestWMIQuery.GetWMIQuery(TestCfgWMIQ, ListaDati);
     }
     if (!EsclCestino)
     {
         TestAltri.GetCestino(ListaDati);
     }
 }
        private JwtSecurityToken CreateToken(string clientId, DateTime?nowOverride = null)
        {
            var certificate = TestCert.Load();
            var now         = nowOverride ?? DateTime.Now;

            var token = new JwtSecurityToken(
                clientId,
                "https://idsrv3.com/connect/token",
                new List <Claim>()
            {
                new Claim("jti", Guid.NewGuid().ToString()),
                new Claim(JwtClaimTypes.Subject, clientId),
                new Claim(JwtClaimTypes.IssuedAt, UnixTime(now).ToString(), ClaimValueTypes.Integer64)
            },
                now,
                now.AddMinutes(1),
                new X509SigningCredentials(certificate)
                );
            var rawCertificate = Convert.ToBase64String(certificate.Export(X509ContentType.Cert));

            token.Header.Add(JwtHeaderParameterNames.X5c, new[] { rawCertificate });
            return(token);
        }
        private JwtSecurityToken CreateToken(string clientId, DateTime?nowOverride = null)
        {
            var certificate = TestCert.Load();
            var now         = nowOverride ?? DateTime.UtcNow;

            var token = new JwtSecurityToken(
                clientId,
                "https://idsrv3.com/connect/token",
                new List <Claim>()
            {
                new Claim("jti", Guid.NewGuid().ToString()),
                new Claim(JwtClaimTypes.Subject, clientId),
                new Claim(JwtClaimTypes.IssuedAt, now.ToEpochTime().ToString(), ClaimValueTypes.Integer64)
            },
                now,
                now.AddMinutes(1),
                new SigningCredentials(
                    new X509SecurityKey(certificate),
                    SecurityAlgorithms.RsaSha256
                    )
                );

            return(token);
        }
        public static List <Client> Get()
        {
            return(new List <Client>
            {
                new Client
                {
                    ClientName = "Disabled client",
                    ClientId = "disabled_client",
                    Enabled = false,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret("secret")
                    }
                },

                new Client
                {
                    ClientName = "Client with no secret set",
                    ClientId = "no_secret_client",
                    Enabled = true
                },

                new Client
                {
                    ClientName = "Client with null secret set",
                    ClientId = "null_secret_client",
                    Enabled = true,
                    ClientSecrets = { new Secret(null) }
                },

                new Client
                {
                    ClientName = "Client with single secret, no protection, no expiration",
                    ClientId = "single_secret_no_protection_no_expiration",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret("secret")
                    }
                },

                new Client
                {
                    ClientName = "Client with X509 Certificate",
                    ClientId = "certificate_valid",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret
                        {
                            Type = IdentityServerConstants.SecretTypes.X509CertificateThumbprint,
                            Value = TestCert.Load().Thumbprint
                        }
                    }
                },

                new Client
                {
                    ClientName = "Client with X509 Certificate",
                    ClientId = "certificate_invalid",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret
                        {
                            Type = IdentityServerConstants.SecretTypes.X509CertificateThumbprint,
                            Value = "invalid"
                        }
                    }
                },

                new Client
                {
                    ClientName = "Client with Base64 encoded X509 Certificate",
                    ClientId = "certificate_base64_valid",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret
                        {
                            Type = IdentityServerConstants.SecretTypes.X509CertificateBase64,
                            Value = Convert.ToBase64String(TestCert.Load().Export(X509ContentType.Cert))
                        }
                    }
                },

                new Client
                {
                    ClientName = "Client with Base64 encoded X509 Certificate",
                    ClientId = "certificate_base64_invalid",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret
                        {
                            Type = IdentityServerConstants.SecretTypes.X509CertificateBase64,
                            Value = "invalid"
                        }
                    }
                },

                new Client
                {
                    ClientName = "Client with single secret, hashed, no expiration",
                    ClientId = "single_secret_hashed_no_expiration",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        // secret
                        new Secret("secret".Sha256())
                    }
                },

                new Client
                {
                    ClientName = "Client with multiple secrets, no protection",
                    ClientId = "multiple_secrets_no_protection",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret("secret"),
                        new Secret("foobar", "some description"),
                        new Secret("quux"),
                        new Secret("notexpired", DateTime.UtcNow.AddDays(1)),
                        new Secret("expired", DateTime.UtcNow.AddDays(-1))
                    }
                },

                new Client
                {
                    ClientName = "Client with multiple secrets, hashed",
                    ClientId = "multiple_secrets_hashed",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        // secret
                        new Secret("secret".Sha256()),
                        // foobar
                        new Secret("foobar".Sha256(), "some description"),
                        // quux
                        new Secret("quux".Sha512()),
                        // notexpired
                        new Secret("notexpired".Sha256(), DateTime.UtcNow.AddDays(1)),
                        // expired
                        new Secret("expired".Sha512(), DateTime.UtcNow.AddDays(-1))
                    },
                },

                new Client
                {
                    ClientName = "MTLS Client with invalid secrets",
                    ClientId = "mtls_client_invalid",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret(@"CN=invalid", "mtls.test")
                        {
                            Type = SecretTypes.X509CertificateName
                        },
                        new Secret("invalid", "mtls.test")
                        {
                            Type = SecretTypes.X509CertificateThumbprint
                        },
                    }
                },

                new Client
                {
                    ClientName = "MTLS Client with valid secrets",
                    ClientId = "mtls_client_valid",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret(@"CN=idsrv3test", "mtls.test")
                        {
                            Type = SecretTypes.X509CertificateName
                        },
                        new Secret("6B7ACC520305BFDB4F7252DAEB2177CC091FAAE1", "mtls.test")
                        {
                            Type = SecretTypes.X509CertificateThumbprint
                        },
                    }
                }
            });
        }
Ejemplo n.º 11
0
 internal static ITokenCreationService CreateDefaultTokenCreator(IdentityServerOptions options = null)
 {
     return(new DefaultTokenCreationService(
                new StubClock(),
                new DefaultKeyMaterialService(
                    new IValidationKeysStore[] { },
                    new ISigningCredentialStore[] { new InMemorySigningCredentialsStore(TestCert.LoadSigningCredentials()) },
                    new NopAutomaticKeyManagerKeyStore()
                    ),
                options ?? TestIdentityServerOptions.Create(),
                TestLogger.Create <DefaultTokenCreationService>()));
 }
Ejemplo n.º 12
0
        public static IEnumerable <Client> Get()
        {
            return(new List <Client>
            {
                ///////////////////////////////////////////
                // Console Client Credentials Flow Sample
                //////////////////////////////////////////
                new Client
                {
                    ClientId = "client",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    AllowOfflineAccess = true,

                    AllowedScopes =
                    {
                        "api1", "api2", "other_api"
                    }
                },
                new Client
                {
                    ClientId = "client.cnf",
                    ClientSecrets =
                    {
                        new Secret
                        {
                            Type = "confirmation.test",
                            Description = "Test for cnf claim",
                            Value = "foo"
                        }
                    },

                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    AllowOfflineAccess = true,

                    AllowedScopes =
                    {
                        "api1", "api2"
                    }
                },
                new Client
                {
                    ClientId = "client.and.ro",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,

                    AllowedScopes =
                    {
                        "openid",
                        "api1", "api2"
                    }
                },
                new Client
                {
                    ClientId = "client.identityscopes",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = GrantTypes.ClientCredentials,

                    AllowedScopes =
                    {
                        "openid", "profile",
                        "api1",   "api2"
                    }
                },
                new Client
                {
                    ClientId = "client.no_default_scopes",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = GrantTypes.ClientCredentials
                },
                new Client
                {
                    ClientId = "client.no_secret",
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    RequireClientSecret = false,
                    AllowedScopes = { "api1" }
                },

                ///////////////////////////////////////////
                // Console Resource Owner Flow Sample
                //////////////////////////////////////////
                new Client
                {
                    ClientId = "roclient",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                    RefreshTokenUsage = TokenUsage.OneTimeOnly,

                    AllowOfflineAccess = true,
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Email,
                        IdentityServerConstants.StandardScopes.Address,
                        "roles",
                        "api1",                                        "api2", "api4.with.roles"
                    }
                },
                new Client
                {
                    ClientId = "roclient.reuse",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

                    AllowOfflineAccess = true,
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Email,
                        IdentityServerConstants.StandardScopes.Address,
                        "roles",
                        "api1",                                        "api2", "api4.with.roles"
                    },

                    RefreshTokenUsage = TokenUsage.ReUse
                },

                /////////////////////////////////////////
                // Console Custom Grant Flow Sample
                ////////////////////////////////////////
                new Client
                {
                    ClientId = "client.custom",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = { "custom", "custom.nosubject" },

                    AllowedScopes =
                    {
                        "api1", "api2"
                    },

                    AllowOfflineAccess = true
                },
                new Client
                {
                    ClientId = "client.dynamic",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = { "dynamic" },

                    AllowedScopes =
                    {
                        "api1", "api2"
                    },

                    AlwaysSendClientClaims = true
                },

                ///////////////////////////////////////////
                // Introspection Client Sample
                //////////////////////////////////////////
                new Client
                {
                    ClientId = "roclient.reference",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

                    AllowOfflineAccess = true,
                    AllowedScopes =
                    {
                        "api1", "api2"
                    },

                    AccessTokenType = AccessTokenType.Reference
                },

                new Client
                {
                    ClientName = "Client with Base64 encoded X509 Certificate",
                    ClientId = "certificate_base64_valid",
                    Enabled = true,

                    ClientSecrets =
                    {
                        new Secret
                        {
                            Type = IdentityServerConstants.SecretTypes.X509CertificateBase64,
                            Value = Convert.ToBase64String(TestCert.Load().Export(X509ContentType.Cert))
                        }
                    },

                    AllowedGrantTypes = GrantTypes.ClientCredentials,

                    AllowedScopes = new List <string>
                    {
                        "api1", "api2"
                    }
                },

                new Client
                {
                    ClientId = "implicit",
                    AllowedGrantTypes = GrantTypes.Implicit,
                    AllowedScopes = { "api1" },
                    RedirectUris = { "http://implicit" }
                },
                new Client
                {
                    ClientId = "implicit_and_client_creds",
                    AllowedGrantTypes = GrantTypes.ImplicitAndClientCredentials,
                    AllowedScopes = { "api1" },
                    RedirectUris = { "http://implicit_and_client_creds" }
                }
            });
        }
        public static List <Client> Get()
        {
            return(new List <Client>
            {
                new Client
                {
                    ClientName = "Disabled client",
                    ClientId = "disabled_client",
                    Enabled = false,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret("secret")
                    }
                },

                new Client
                {
                    ClientName = "Client with no secret set",
                    ClientId = "no_secret_client",
                    Enabled = true
                },

                new Client
                {
                    ClientName = "Client with single secret, no protection, no expiration",
                    ClientId = "single_secret_no_protection_no_expiration",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret("secret")
                    }
                },

                new Client
                {
                    ClientName = "Client with X509 Certificate",
                    ClientId = "certificate_valid",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret
                        {
                            Type = Constants.SecretTypes.X509CertificateThumbprint,
                            Value = TestCert.Load().Thumbprint
                        }
                    }
                },

                new Client
                {
                    ClientName = "Client with X509 Certificate",
                    ClientId = "certificate_invalid",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret
                        {
                            Type = Constants.SecretTypes.X509CertificateThumbprint,
                            Value = "invalid"
                        }
                    }
                },

                new Client
                {
                    ClientName = "Client with Base64 encoded X509 Certificate",
                    ClientId = "certificate_base64_valid",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret
                        {
                            Type = Constants.SecretTypes.X509CertificateBase64,
                            Value = Convert.ToBase64String(TestCert.Load().Export(X509ContentType.Cert))
                        }
                    }
                },

                new Client
                {
                    ClientName = "Client with Base64 encoded X509 Certificate",
                    ClientId = "certificate_base64_invalid",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret
                        {
                            Type = Constants.SecretTypes.X509CertificateBase64,
                            Value = "invalid"
                        }
                    }
                },

                new Client
                {
                    ClientName = "Client with single secret, hashed, no expiration",
                    ClientId = "single_secret_hashed_no_expiration",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        // secret
                        new Secret("secret".Sha256())
                    }
                },

                new Client
                {
                    ClientName = "Client with multiple secrets, no protection",
                    ClientId = "multiple_secrets_no_protection",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret("secret"),
                        new Secret("foobar", "some description"),
                        new Secret("quux"),
                        new Secret("notexpired", DateTimeOffset.UtcNow.AddDays(1)),
                        new Secret("expired", DateTimeOffset.UtcNow.AddDays(-1)),
                    }
                },

                new Client
                {
                    ClientName = "Client with multiple secrets, hashed",
                    ClientId = "multiple_secrets_hashed",
                    Enabled = true,

                    ClientSecrets = new List <Secret>
                    {
                        // secret
                        new Secret("secret".Sha256()),
                        // foobar
                        new Secret("foobar".Sha256(), "some description"),
                        // quux
                        new Secret("quux".Sha512()),
                        // notexpired
                        new Secret("notexpired".Sha256(), DateTimeOffset.UtcNow.AddDays(1)),
                        // expired
                        new Secret("expired".Sha512(), DateTimeOffset.UtcNow.AddDays(-1)),
                    }
                },
            });
        }
Ejemplo n.º 14
0
        public static TokenValidator CreateTokenValidator(IReferenceTokenStore store = null, IProfileService profile = null)
        {
            if (profile == null)
            {
                profile = new TestProfileService();
            }

            if (store == null)
            {
                store = CreateReferenceTokenStore();
            }

            var clients = CreateClientStore();
            var options = TestIdentityServerOptions.Create();
            var context = new MockHttpContextAccessor(options);
            var logger  = TestLogger.Create <TokenValidator>();

            var validator = new TokenValidator(
                clients: clients,
                referenceTokenStore: store,
                customValidator: new DefaultCustomTokenValidator(
                    profile: profile,
                    clients: clients,
                    logger: TestLogger.Create <DefaultCustomTokenValidator>()),
                keys: new DefaultKeyMaterialService(new[] { new DefaultValidationKeysStore(new[] { TestCert.LoadSigningCredentials().Key }) }),
                logger: logger,
                options: options,
                context: context);

            return(validator);
        }
Ejemplo n.º 15
0
 internal static ITokenCreationService CreateDefaultTokenCreator()
 {
     return(new DefaultTokenCreationService(
                new DefaultKeyMaterialService(new IValidationKeysStore[] { }, new DefaultSigningCredentialsStore(TestCert.LoadSigningCredentials()))));
 }
Ejemplo n.º 16
0
        internal static ITokenCreationService CreateDefaultTokenCreator(IdentityServerOptions options = null)
        {
            options = options ?? new IdentityServerOptions();

            return(new DefaultTokenCreationService(
                       options,
                       new DefaultKeyMaterialService(new IValidationKeysStore[] { }, new DefaultSigningCredentialsStore(TestCert.LoadSigningCredentials())), TestLogger.Create <DefaultTokenCreationService>()));
        }
Ejemplo n.º 17
0
        public static IEnumerable <Client> Get()
        {
            return(new List <Client>
            {
                ///////////////////////////////////////////
                // Console Client Credentials Flow Sample
                //////////////////////////////////////////
                new Client
                {
                    ClientId = "client",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = GrantTypes.ClientCredentials,

                    AllowedScopes =
                    {
                        "api1", "api2"
                    }
                },
                new Client
                {
                    ClientId = "client.identityscopes",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = GrantTypes.ClientCredentials,

                    AllowedScopes =
                    {
                        "openid", "profile",
                        "api1",   "api2"
                    }
                },
                new Client
                {
                    ClientId = "client.no_default_scopes",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    AllowAccessToAllScopes = true
                },

                ///////////////////////////////////////////
                // Console Resource Owner Flow Sample
                //////////////////////////////////////////
                new Client
                {
                    ClientId = "roclient",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

                    AllowOfflineAccess = true,
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Email,
                        IdentityServerConstants.StandardScopes.Address,
                        "roles",
                        "api1",                                        "api2", "api4.with.roles"
                    }
                },

                /////////////////////////////////////////
                // Console Custom Grant Flow Sample
                ////////////////////////////////////////
                new Client
                {
                    ClientId = "client.custom",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = GrantTypes.List("custom"),

                    AllowedScopes =
                    {
                        "api1", "api2"
                    }
                },

                ///////////////////////////////////////////
                // Introspection Client Sample
                //////////////////////////////////////////
                new Client
                {
                    ClientId = "roclient.reference",
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

                    AllowOfflineAccess = true,
                    AllowedScopes =
                    {
                        "api1", "api2"
                    },

                    AccessTokenType = AccessTokenType.Reference
                },

                new Client
                {
                    ClientName = "Client with Base64 encoded X509 Certificate",
                    ClientId = "certificate_base64_valid",
                    Enabled = true,

                    ClientSecrets =
                    {
                        new Secret
                        {
                            Type = IdentityServerConstants.SecretTypes.X509CertificateBase64,
                            Value = Convert.ToBase64String(TestCert.Load().Export(X509ContentType.Cert))
                        }
                    },

                    AllowedGrantTypes = GrantTypes.ClientCredentials,

                    AllowedScopes = new List <string>
                    {
                        "api1", "api2"
                    },
                },
            });
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Tries to find a matching certificate on this machine from the the serial number of one of the
        /// certificates in the mobile provision (the one in the mobileprovision is missing the public/private key pair)
        /// </summary>
        public static X509Certificate2 FindCertificate(MobileProvision ProvisionToWorkFrom)
        {
            Program.LogVerbose("  Looking for a certificate that matches the application identifier '{0}'", ProvisionToWorkFrom.ApplicationIdentifier);

            X509Certificate2 Result = null;

            if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX)
            {
                // run certtool y to get the currently installed certificates
                CertToolData = "";
                Process CertTool = new Process();
                CertTool.StartInfo.FileName               = "/usr/bin/security";
                CertTool.StartInfo.UseShellExecute        = false;
                CertTool.StartInfo.Arguments              = "find-identity -p codesigning -v";
                CertTool.StartInfo.RedirectStandardOutput = true;
                CertTool.OutputDataReceived              += new DataReceivedEventHandler(OutputReceivedCertToolProcessCall);
                CertTool.Start();
                CertTool.BeginOutputReadLine();
                CertTool.WaitForExit();
                if (CertTool.ExitCode == 0)
                {
                    foreach (X509Certificate2 SourceCert in ProvisionToWorkFrom.DeveloperCertificates)
                    {
                        X509Certificate2 ValidInTimeCert = null;
                        // see if certificate can be found by serial number
                        string CertHash = SourceCert.GetCertHashString();

                        if (CertToolData.Contains(CertHash))
                        {
                            ValidInTimeCert = SourceCert;
                        }

                        if (ValidInTimeCert != null)
                        {
                            int StartIndex = SourceCert.SubjectName.Name.IndexOf("CN=") + 3;
                            int EndIndex   = SourceCert.SubjectName.Name.IndexOf(", ", StartIndex);
                            SourceCert.FriendlyName = SourceCert.SubjectName.Name.Substring(StartIndex, EndIndex - StartIndex);

                            // Found a cert in the valid time range, quit now!
                            Result = ValidInTimeCert;
                            break;
                        }
                    }
                }
            }
            else
            {
                // Open the personal certificate store on this machine
                X509Store Store = new X509Store();
                Store.Open(OpenFlags.ReadOnly);

                // Try finding a matching certificate from the serial number (the one in the mobileprovision is missing the public/private key pair)
                foreach (X509Certificate2 SourceCert in ProvisionToWorkFrom.DeveloperCertificates)
                {
                    X509Certificate2Collection FoundCerts = Store.Certificates.Find(X509FindType.FindBySerialNumber, SourceCert.SerialNumber, false);

                    Program.LogVerbose("  .. Provision entry SN '{0}' matched {1} installed certificate(s)", SourceCert.SerialNumber, FoundCerts.Count);

                    X509Certificate2 ValidInTimeCert = null;
                    foreach (X509Certificate2 TestCert in FoundCerts)
                    {
                        //@TODO: Pretty sure the certificate information from the library is in local time, not UTC and this works as expected, but it should be verified!
                        DateTime EffectiveDate  = TestCert.NotBefore;
                        DateTime ExpirationDate = TestCert.NotAfter;
                        DateTime Now            = DateTime.Now;

                        bool bCertTimeIsValid = (EffectiveDate < Now) && (ExpirationDate > Now);

                        Program.LogVerbose("  .. .. Installed certificate '{0}' is {1} (range '{2}' to '{3}')", TestCert.FriendlyName, bCertTimeIsValid ? "valid (choosing it)" : "EXPIRED", TestCert.GetEffectiveDateString(), TestCert.GetExpirationDateString());
                        if (bCertTimeIsValid)
                        {
                            ValidInTimeCert = TestCert;
                            break;
                        }
                    }

                    if (ValidInTimeCert != null)
                    {
                        // Found a cert in the valid time range, quit now!
                        Result = ValidInTimeCert;
                        break;
                    }
                }

                Store.Close();
            }

            if (Result == null)
            {
                Program.LogVerbose("  .. Failed to find a valid certificate that was in date");
            }

            return(Result);
        }
Ejemplo n.º 19
0
 internal static ITokenCreationService CreateDefaultTokenCreator()
 {
     return(new DefaultTokenCreationService(
                new StubClock(),
                new DefaultKeyMaterialService(new IValidationKeysStore[] { },
                                              new DefaultSigningCredentialsStore(TestCert.LoadSigningCredentials())),
                TestIdentityServerOptions.Create(),
                TestLogger.Create <DefaultTokenCreationService>()));
 }
Ejemplo n.º 20
0
 internal static ITokenCreationService CreateDefaultTokenCreator()
 {
     return(new DefaultTokenCreationService(
                new InMemorySigningCredentialsStore(TestCert.LoadSigningCredentials())));
 }
        public JwtRequestAuthorizeTests()
        {
            IdentityModelEventSource.ShowPII = true;

            _rsaKey = CryptoHelper.CreateRsaSecurityKey();

            _mockPipeline.Clients.AddRange(new Client[]
            {
                _client = new Client
                {
                    ClientName           = "Client with keys",
                    ClientId             = "client",
                    Enabled              = true,
                    RequireRequestObject = true,

                    RedirectUris = { "https://client/callback" },

                    ClientSecrets =
                    {
                        new Secret
                        {
                            // x509 cert as base64 string
                            Type  = IdentityServerConstants.SecretTypes.X509CertificateBase64,
                            Value = Convert.ToBase64String(TestCert.Load().Export(X509ContentType.Cert))
                        },
                        new Secret
                        {
                            // symmetric key as JWK
                            Type  = IdentityServerConstants.SecretTypes.JsonWebKey,
                            Value = _symmetricJwk
                        },
                        new Secret
                        {
                            // RSA key as JWK
                            Type  = IdentityServerConstants.SecretTypes.JsonWebKey,
                            Value = JsonConvert.SerializeObject(JsonWebKeyConverter.ConvertFromRSASecurityKey(_rsaKey))
                        },
                        new Secret
                        {
                            // x509 cert as JWK
                            Type  = IdentityServerConstants.SecretTypes.JsonWebKey,
                            Value = JsonConvert.SerializeObject(JsonWebKeyConverter.ConvertFromX509SecurityKey(new X509SecurityKey(TestCert.Load())))
                        }
                    },

                    AllowedGrantTypes = GrantTypes.Implicit,

                    AllowedScopes = new List <string>
                    {
                        "openid", "profile", "api1", "api2"
                    }
                },
            });

            _mockPipeline.Users.Add(new TestUser
            {
                SubjectId = "bob",
                Username  = "******",
                Claims    = new Claim[]
                {
                    new Claim("name", "Bob Loblaw"),
                    new Claim("email", "*****@*****.**"),
                    new Claim("role", "Attorney")
                }
            });

            _mockPipeline.IdentityScopes.AddRange(new IdentityResource[] {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
                new IdentityResources.Email()
            });
            _mockPipeline.ApiScopes.AddRange(new ApiResource[] {
                new ApiResource
                {
                    Name   = "api",
                    Scopes =
                    {
                        new Scope
                        {
                            Name = "api1"
                        },
                        new Scope
                        {
                            Name = "api2"
                        }
                    }
                }
            });

            _mockPipeline.Initialize();
        }