public static StoredGrant CreateRefreshTokenHandle(
            string subject,
            Client client,
            Application application,
            IEnumerable<Claim> claims,
            IEnumerable<Scope> scopes,
            DateTime expiration,
            bool createRefreshToken = false)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (application == null) throw new ArgumentNullException("application");
            if (claims == null) throw new ArgumentNullException("claims");
            if (scopes == null) throw new ArgumentNullException("scopes");

            return new StoredGrant
            {
                Type = StoredGrantType.RefreshTokenIdentifier,
                Subject = subject,
                Client = client,
                Application = application,
                ResourceOwner = claims.ToStoredGrantClaims().ToList(),
                Scopes = scopes.ToList(),
                Created = DateTime.UtcNow,
                Expiration = expiration,
                CreateRefreshToken = createRefreshToken
            };
        }
        public static StoredGrant CreateAuthorizationCode(
            Client client, 
            Application application, 
            string redirectUri, 
            IEnumerable<Claim> claims, 
            IEnumerable<Scope> scopes, 
            bool createRefreshToken,
            DateTime? refreshTokenExpiration = null,
            DateTime? expiration = null)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (application == null) throw new ArgumentNullException("application");
            if (claims == null) throw new ArgumentNullException("claims");
            if (scopes == null) throw new ArgumentNullException("scopes");

            return new StoredGrant
            {
                Type = StoredGrantType.AuthorizationCode,
                Client = client,
                Application = application,
                RedirectUri = redirectUri,
                ResourceOwner = claims.ToStoredGrantClaims().ToList(),
                Scopes = scopes.ToList(),
                Created = DateTime.UtcNow,
                Expiration = DateTime.UtcNow.AddHours(1),
                CreateRefreshToken = createRefreshToken,
                RefreshTokenExpiration = createRefreshToken ? refreshTokenExpiration : null
            };
        }
        public StoredGrant Find(string subject, Client client, Application application, IEnumerable<Scope> scopes, StoredGrantType type)
        {
            var grants = db.StoredGrants.Where(h => h.Subject == subject &&
                                                             h.Client.ClientId == client.ClientId &&
                                                             h.Application.ID == application.ID &&
                                                             h.Type == type).ToList();

            return grants.FirstOrDefault(grant => grant.Scopes.ScopeEquals(scopes));
        }
        private static Client CreateMockClient()
        {
            var clientId = "JohnSmithMobileDevShop";

            var client = new Client
            {
                Name = "John Smith's Mobile Development Shop",
                ClientId = clientId,
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                Flow = OAuthFlow.ResourceOwner,
                AllowRefreshToken = false
            };
            client.SetSharedSecret("MyTestSecret");
            return client;
        }
        public static TokenHandle CreateConsentDecisionHandle(string subject, Client client, Application application, IEnumerable<Scope> scopes)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (application == null) throw new ArgumentNullException("application");
            if (scopes == null) throw new ArgumentNullException("scopes");

            return new TokenHandle
            {
                Type = TokenHandleType.ConsentDecision,
                Subject = subject,
                Client = client,
                Application = application, 
                Scopes = scopes.ToList(),
                Created = DateTime.UtcNow
            };
        }
        public static StoredGrant CreateConsentDecision(string subject, Client client, Application application, IEnumerable<Scope> scopes)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (application == null) throw new ArgumentNullException("application");
            if (scopes == null) throw new ArgumentNullException("scopes");

            return new StoredGrant
            {
                Type = StoredGrantType.ConsentDecision,
                Subject = subject,
                Client = client,
                Application = application, 
                Scopes = scopes.ToList(),
                Created = DateTime.UtcNow,
                Expiration = DateTime.UtcNow.AddYears(5)
            };
        }
        private void PopulateData()
        {
            var resourceOwnerClient = new Client
            {
                Name = "Resource Owner Flow Client",
                ClientId = "roclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,
                Flow = OAuthFlow.ResourceOwner,
                AllowRefreshToken = true
            };

            var codeClient = new Client
            {
                Name = "Code Flow Client",
                ClientId = "codeclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                AllowRefreshToken = true,
                Flow = OAuthFlow.Code,

                RedirectUris = new List<ClientRedirectUri>
                    {
                        new ClientRedirectUri
                        {
                            Uri = "https://prod.local",
                            Description = "Production"
                        },
                        new ClientRedirectUri
                        {
                            Uri = "https://test.local",
                            Description = "Test"
                        }
                    }
            };

            var implicitClient = new Client
            {
                Name = "Implicit Flow Client",
                ClientId = "implicitclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                AllowRefreshToken = false,
                Flow = OAuthFlow.Implicit,

                RedirectUris = new List<ClientRedirectUri> 
                    {
                        new ClientRedirectUri
                        {
                            Uri = "https://test2.local",
                            Description = "Test"
                        }
                    }
            };

            var trustedClient = new Client
            {
                Name = "Trusted Client",
                ClientId = "trustedclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                AllowRefreshToken = false,
                Flow = OAuthFlow.ResourceOwner,
            };

            var readScope = new Scope
            {
                AllowedClients = new List<Client> { codeClient, implicitClient, resourceOwnerClient },
                Name = "read",
                Description = "Read data",
                Emphasize = false
            };

            var browseScope = new Scope
            {
                AllowedClients = new List<Client> { codeClient, implicitClient, resourceOwnerClient },
                Name = "browse",
                Description = "Browse data",
                Emphasize = false
            };

            var searchScope = new Scope
            {
                AllowedClients = new List<Client> { codeClient, resourceOwnerClient },
                Name = "search",
                Description = "Search data",
                Emphasize = false
            };

            var writeScope = new Scope
            {
                AllowedClients = new List<Client> { resourceOwnerClient },
                Name = "write",
                Description = "write data",
                Emphasize = true
            };

            var deleteScope = new Scope
            {
                AllowedClients = new List<Client> { trustedClient },
                Name = "delete",
                Description = "delete data",
                Emphasize = true
            };

            var application = new Application
            {
                Name = "Test Application",
                Namespace = "test",
                Scopes = new List<Scope> { readScope, browseScope, searchScope, writeScope, deleteScope },
                RequireConsent = true,
                TokenLifetime = 60
            };
            
            _applications.Add(application);
        }
        public HttpResponseMessage Post(ClientModel model)
        {
            if (String.IsNullOrEmpty(model.ClientSecret))
            {
                ModelState.AddModelError("model.ClientSecret", "ClientSecret is required");
            }

            if (!ModelState.IsValid)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
            }

            if (config.Clients.All.Any(x => x.ClientId == model.ClientId))
            {
                ModelState.AddModelError("", "That Client ID is already in use.");
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
            }
            if (config.Clients.All.Any(x => x.Name == model.Name))
            {
                ModelState.AddModelError("", "That Name is already in use.");
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
            }

            var item = new Client();
            item.ClientId = model.ClientId;
            item.Name = model.Name;
            item.Flow = model.Flow;
            item.AllowRefreshToken = model.AllowRefreshToken;
            item.RequireConsent = model.RequireConsent;
            item.Enabled = model.Enabled;
            item.SetSharedSecret(model.ClientSecret);
            
            this.config.Clients.Add(item);
            this.config.SaveChanges();

            var response = Request.CreateResponse(HttpStatusCode.OK, item);
            var url = Url.Link("Admin-Endpoints", new { controller = "Clients", id = item.ClientId });
            response.Headers.Location = new Uri(url);
            return response;
        }
        public static void Populate()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<AuthorizationServerContext>());

            try
            {
                var db = DependencyResolver.Current.GetService<AuthorizationServerContext>();

                var resourceOwnerClient = db.Clients.Find("roclient");
                var CodeClient = db.Clients.Find("codeclient");
                var ImplicitClient = db.Clients.Find("implicitclient");
                var client = db.Clients.Find("client");
                var assertionClient = db.Clients.Find("assertionclient");

                if (client == null)
                {
                    client = new Client
                    {
                        Enabled = true,
                        Name = "Client",
                        ClientId = "client",
                        Flow = OAuthFlow.Client
                    };
                    client.SetSharedSecret("secret");
                    db.Clients.Add(client);
                    db.SaveChanges();
                }

                if (assertionClient == null)
                {
                    assertionClient = new Client
                    {
                        Enabled = true,
                        Name = "Assertion Client",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,
                        ClientId = "assertionclient",
                        Flow = OAuthFlow.Assertion
                    };
                    assertionClient.SetSharedSecret("secret");
                    db.Clients.Add(assertionClient);
                    db.SaveChanges();
                }

                if (resourceOwnerClient == null)
                {
                    resourceOwnerClient = new Client
                    {
                        Enabled = true,
                        Name = "Resource Owner Flow Client",
                        ClientId = "roclient",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,
                        Flow = OAuthFlow.ResourceOwner,
                        AllowRefreshToken = true
                    };
                    resourceOwnerClient.SetSharedSecret("secret");
                    db.Clients.Add(resourceOwnerClient);
                    db.SaveChanges();
                }
                if (CodeClient == null)
                {
                    CodeClient = new Client
                    {
                        Enabled = true,
                        Name = "Code Flow Client",
                        ClientId = "codeclient",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                        AllowRefreshToken = true,
                        Flow = OAuthFlow.Code,

                        RedirectUris = new List<ClientRedirectUri> 
                        {
                            new ClientRedirectUri
                            {
                                Uri = "https://prod.local",
                                Description = "Production"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "https://test.local",
                                Description = "Test"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "https://localhost:44303/callback",
                                Description = "Local Test"
                            }
                        }
                    };
                    CodeClient.SetSharedSecret("secret");
                    db.Clients.Add(CodeClient);
                    db.SaveChanges();
                }
                if (ImplicitClient == null)
                {
                    ImplicitClient = new Client
                    {
                        Enabled = true,
                        Name = "Implicit Flow Client",
                        ClientId = "implicitclient",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                        AllowRefreshToken = false,
                        Flow = OAuthFlow.Implicit,

                        RedirectUris = new List<ClientRedirectUri>
                        {
                            new ClientRedirectUri
                            {
                                Uri = "https://test2.local",
                                Description = "Test"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "https://localhost:44300/callback.cshtml",
                                Description = "JavaScript Callback Page"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "ms-app://s-1-15-2-4224567138-2162094511-1976135278-3909242924-69295690-1380993013-1329561029/",
                                Description = "Win Store App"
                            }
                        }
                    };
                    ImplicitClient.SetSharedSecret("secret");
                    db.Clients.Add(ImplicitClient);
                    db.SaveChanges();
                }

                //if (!db.SigningKeys.Any())
                //{
                //    db.SigningKeys.Add(new X509CertificateReference
                //    {
                //        Name = "Default X509 Cert",
                //        Location = System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
                //        FindValue = "CN=idsrv.local",
                //        FindType = System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectDistinguishedName,
                //        StoreName = System.Security.Cryptography.X509Certificates.StoreName.My
                //    });
                //    db.SaveChanges();
                //}

                if (!db.Applications.Any())
                {
                    var readScope = new Scope
                    {
                        AllowedClients = new List<Client> { CodeClient, ImplicitClient, resourceOwnerClient, client, assertionClient },
                        Name = "read",
                        DisplayName = "Read data",
                        Description = "Allows to read data",
                        Emphasize = false
                    };

                    var searchScope = new Scope
                    {
                        AllowedClients = new List<Client> { CodeClient, resourceOwnerClient },
                        Name = "search",
                        DisplayName = "Search data",
                        Description = "Allows to search for data",
                        Emphasize = false
                    };

                    var writeScope = new Scope
                    {
                        AllowedClients = new List<Client> { resourceOwnerClient },
                        Name = "write",
                        DisplayName = "Write data",
                        Description = "Allows to write data",
                        Emphasize = true
                    };

                    var key = new SymmetricKey { Name = "Demo signing key" };
                    key.SetValue(Convert.FromBase64String("1fTiS2clmPTUlNcpwYzd5i4AEFJ2DEsd8TcUsllmaKQ="));

                    var application = new Application
                    {
                        Enabled = true,
                        Name = "User management",
                        Namespace = "users",
                        Audience = "users",
                        Description = "This app manages your users",
                        LogoUrl = "http://en.opensuse.org/images/0/0b/Icon-user.png",
                        Scopes = new List<Scope> { readScope, searchScope, writeScope },
                        RequireConsent = true,
                        TokenLifetime = 60,
                        AllowRefreshToken = true,
                        AllowRememberConsentDecision = true,
                        SigningKey = key
                    };
                    
                    db.Applications.Add(application);
                    db.SaveChanges();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
 public StoredGrant Find(string subject, Client client, Application application, System.Collections.Generic.IEnumerable<Scope> scopes, StoredGrantType type)
 {
     throw new System.NotImplementedException();
 }
        static void Main(string[] args)
        {
            using (var db = new EFAuthorizationServerConfigurationContext())
            {
                db.Database.Delete();
            }

            using (var db = new EFAuthorizationServerConfigurationContext())
            {
                Console.WriteLine(db.Database.Connection.ConnectionString);

                if (!db.SigningKeys.Any())
                {
                    db.SigningKeys.Add(new X509CertificateReference
                    {
                        Location = System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
                        FindType = System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectDistinguishedName,
                        StoreName = System.Security.Cryptography.X509Certificates.StoreName.My,
                        FindValue = "CN=sts"
                    });
                    db.SigningKeys.Add(new SymmetricKey { Value = new byte[] { 1, 2, 3, 4 } });
                    db.SaveChanges();
                }

                if (!db.Clients.Any())
                {
                    var client1 = new Client
                    {
                        ClientId = "client1",
                        Name = "Test Client1",
                        RedirectUris = new List<ClientRedirectUri>()
                        {
                            new ClientRedirectUri{ Description = "Test1", Uri = "http://test1"}
                        }
                    };
                    var client2 = new Client
                    {
                        ClientId = "client2",
                        Name = "Test Client2",
                        RedirectUris = new List<ClientRedirectUri>()
                        {
                            new ClientRedirectUri{ Description = "Test2", Uri = "http://test2"}
                        }
                    };
                    db.Clients.Add(client1);
                    db.Clients.Add(client2);
                    db.SaveChanges();
                }

                //var c1 = db.Clients.Find("client1");
                //if (c1 != null)
                //{
                //    db.Clients.Remove(c1);
                //    db.SaveChanges();
                //}

                if (!db.Applications.Any())
                {
                    var c1 = db.Clients.OrderBy(x => x.ClientId).Skip(0).Take(1).First();
                    var c2 = db.Clients.OrderBy(x => x.ClientId).Skip(1).Take(1).First();
                    var key = db.SigningKeys.First();

                    var app = new Application
                    {
                        Name = "Test App",
                        Scopes = new List<Scope>()
                        {
                            new Scope{ Name = "edit", 
                                AllowedClients = new List<Client>{c1} },
                            new Scope{ Name = "view", 
                                AllowedClients = new List<Client>{c2} },
                        },
                        SigningKey = key
                       
                    };
                    db.Applications.Add(app);
                    db.SaveChanges();
                }

                var a1 = db.Applications.First();
                if (a1 != null)
                {
                    foreach (var c in a1.Clients)
                    {
                        Console.WriteLine(c.Name);
                    }
                    if (a1.SigningKey != null)
                    {
                        var creds = a1.SigningKey.GetSigningCredentials();
                    }

                    //db.Applications.Remove(a1);
                    //db.SaveChanges();
                }

                //var client = db.Clients.First();
                //if (client != null)
                //{
                //    db.Clients.Remove(client);
                //    db.SaveChanges();
                //}
            }
        }
        private void PopulateData()
        {
            var resourceOwnerClient = new Client
            {
                Name = "Resource Owner Flow Client",
                ClientId = "roclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,
                Flow = OAuthFlow.ResourceOwner,
                AllowRefreshToken = true
            };

            var CodeClient = new Client
            {
                Name = "Code Flow Client",
                ClientId = "codeclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                AllowRefreshToken = true,
                Flow = OAuthFlow.Code,

                RedirectUris = new RedirectUris 
                    {
                        new RedirectUri
                        {
                            Uri = "https://prod.local",
                            Description = "Production"
                        },
                        new RedirectUri
                        {
                            Uri = "https://test.local",
                            Description = "Test"
                        }
                    }
            };

            var ImplicitClient = new Client
            {
                Name = "Implicit Flow Client",
                ClientId = "implicitclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                AllowRefreshToken = false,
                Flow = OAuthFlow.Implicit,

                RedirectUris = new RedirectUris 
                    {
                        new RedirectUri
                        {
                            Uri = "https://test2.local",
                            Description = "Test"
                        }
                    }
            };

            var readScope = new Scope
            {
                AllowedClients = new Clients { CodeClient, ImplicitClient, resourceOwnerClient },
                Name = "read",
                Description = "Read data",
                Emphasize = false
            };

            var searchScope = new Scope
            {
                AllowedClients = new Clients { CodeClient, resourceOwnerClient },
                Name = "search",
                Description = "Search data",
                Emphasize = false
            };

            var writeScope = new Scope
            {
                AllowedClients = new Clients { resourceOwnerClient },
                Name = "write",
                Description = "write data",
                Emphasize = true
            };

            var application = new Application
            {
                Name = "User management",
                Namespace = "users",
                Scopes = new Scopes { readScope, searchScope, writeScope },
                Clients = new Clients { CodeClient, ImplicitClient, resourceOwnerClient },
                ShowConsent = true,
                TokenLifetime = 60
            };

            _applications.Add(application);
        }
        public void Init()
        {
            DataProtectection.Instance = new NoProtection();
            globalConfiguration = new GlobalConfiguration() { Issuer = "Test Issuer" };

            rocv = new Mock<IResourceOwnerCredentialValidation>();
            config = new Mock<IAuthorizationServerConfiguration>();
            handleManager = new Mock<IStoredGrantManager>();
            assertionGrantValidator = new Mock<IAssertionGrantValidation>();
            clientManager = new Mock<IClientManager>();

            tokenService = new TokenService(globalConfiguration);


            #region Setup Test Client
            string secret = "12345678";
            byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(secret);
            string base64EncodedSecret = Convert.ToBase64String(encodedByte);
            _Client = new Client()
            {
                ClientId = "MobileAppShop",
                ClientSecret = base64EncodedSecret,
                Flow = OAuthFlow.ResourceOwner,
                AllowRefreshToken = true
            };
            #endregion

            #region Setup Test Application
            var scope = new Scope();
            scope.Name = "read";
            scope.AllowedClients = new List<Client>();
            scope.AllowedClients.Add(_Client);
            _Scopes = new List<Scope>();
            _Scopes.Add(scope);

            string symmetricKey = "C33333333333333333333333335=";
            byte[] keybytes = Convert.FromBase64String(symmetricKey);
            SecurityKey securityKey = new InMemorySymmetricSecurityKey(keybytes);
            _Application = new Application()
            {
                Name = "Test Application 1",
                Scopes = _Scopes,
                Audience = "Test Audience",
                TokenLifetime = 1,
                AllowRefreshToken = true,
            };
            #endregion

            #region Setup Example StoredGrant
            Claim[] resourceOwnerClaims = { new Claim("Username", "JohnSmith"), new Claim("sub", "JohnSmith") };
            _StoredGrant = new StoredGrant() 
            { 
                GrantId = "MyFavouriteRefrehToken1234",
                CreateRefreshToken = true,
                Client = _Client,
                ResourceOwner = resourceOwnerClaims.ToStoredGrantClaims().ToList(),
                Expiration = DateTime.Now.AddDays(1),
                RefreshTokenExpiration = DateTime.Now.AddMonths(1),
                Type = StoredGrantType.RefreshTokenIdentifier,
                Scopes = _Scopes,
                Application = _Application
            };
            #endregion

            #region Setup Mocking Objects
            // IAuthorizationServerConfiguration
            config.Setup(x => x.FindApplication(It.IsNotNull<string>()))
                .Returns((string name) =>
                {
                    return _Application;
                });
            config.Setup(x => x.GlobalConfiguration).Returns(() => globalConfiguration);

            // IClientManager
            clientManager.Setup(x => x.Get(It.IsNotNull<string>()))
                .Returns((string clientId) =>
                {
                    return _Client;
                });

            // IResourceOwnerCredentialValidation
            rocv.Setup(x => x.Validate(It.IsNotNull<string>(), It.IsNotNull<string>()))
                .Returns((string username, string password) =>
                {
                    return Principal.Create("Test", resourceOwnerClaims);
                });

            // IStoredGrantManager
            handleManager.Setup(x => x.Get(It.IsNotNull<string>()))
                .Returns((string grantIdentifier) => 
                {
                    return _StoredGrant;
                });

            #endregion

            _TokenController = new TokenController(
                rocv.Object,
                config.Object,
                handleManager.Object,
                assertionGrantValidator.Object,
                tokenService,
                clientManager.Object);
            _TokenController.Request = new HttpRequestMessage();
            _TokenController.Request.SetConfiguration(new HttpConfiguration());
        }
 public TokenHandle Find(string subject, Client client, Application application, System.Collections.Generic.IEnumerable<Scope> scopes, TokenHandleType type)
 {
     throw new System.NotImplementedException();
 }
        public static void Populate()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<AuthorizationServerContext>());

            try
            {
                var db = DependencyResolver.Current.GetService<Thinktecture.AuthorizationServer.EF.AuthorizationServerContext>();
                if (!db.GlobalConfiguration.Any())
                {
                    var config = new GlobalConfiguration
                    {
                        AuthorizationServerName = "Thinktecture AuthorizationServer",
                        Issuer = "ThinktectureAuthorizationServer",
                        Administrators = new List<AuthorizationServerAdministrator>
                            {
                                new AuthorizationServerAdministrator{NameID="dominick"},
                                new AuthorizationServerAdministrator{NameID="brock"},
                            }
                    };
                    db.GlobalConfiguration.Add(config);
                    db.SaveChanges();
                }

                var resourceOwnerClient = db.Clients.Find("roclient");
                var CodeClient = db.Clients.Find("codeclient");
                var ImplicitClient = db.Clients.Find("implicitclient");
                var client = db.Clients.Find("client");

                if (client == null)
                {
                    client = new Client
                    {
                        Enabled = true,
                        Name = "Client",
                        ClientId = "client",
                        ClientSecret = "secret",
                        Flow = OAuthFlow.Client
                    };
                    db.Clients.Add(client);
                    db.SaveChanges();
                }

                if (resourceOwnerClient == null)
                {
                    resourceOwnerClient = new Client
                    {
                        Enabled = true,
                        Name = "Resource Owner Flow Client",
                        ClientId = "roclient",
                        ClientSecret = "secret",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,
                        Flow = OAuthFlow.ResourceOwner,
                        AllowRefreshToken = true
                    };
                    db.Clients.Add(resourceOwnerClient);
                    db.SaveChanges();
                }
                if (CodeClient == null)
                {
                    CodeClient = new Client
                    {
                        Enabled = true,
                        Name = "Code Flow Client",
                        ClientId = "codeclient",
                        ClientSecret = "secret",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                        AllowRefreshToken = true,
                        Flow = OAuthFlow.Code,

                        RedirectUris = new List<ClientRedirectUri> 
                        {
                            new ClientRedirectUri
                            {
                                Uri = "https://prod.local",
                                Description = "Production"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "https://test.local",
                                Description = "Test"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "https://localhost:44303/callback",
                                Description = "Local Test"
                            }
                        }
                    };
                    db.Clients.Add(CodeClient);
                    db.SaveChanges();
                }
                if (ImplicitClient == null)
                {
                    ImplicitClient = new Client
                    {
                        Enabled = true,
                        Name = "Implicit Flow Client",
                        ClientId = "implicitclient",
                        ClientSecret = "secret",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                        AllowRefreshToken = false,
                        Flow = OAuthFlow.Implicit,

                        RedirectUris = new List<ClientRedirectUri>
                        {
                            new ClientRedirectUri
                            {
                                Uri = "https://test2.local",
                                Description = "Test"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "ms-app://s-1-15-2-4224567138-2162094511-1976135278-3909242924-69295690-1380993013-1329561029/",
                                Description = "Win Store App"
                            }
                        }
                    };
                    db.Clients.Add(ImplicitClient);
                    db.SaveChanges();
                }

                if (!db.SigningKeys.Any())
                {
                    db.SigningKeys.Add(new X509CertificateReference
                    {
                        Name = "Default X509 Cert",
                        Location = System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
                        FindValue = "CN=idsrv.local",
                        FindType = System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectDistinguishedName,
                        StoreName = System.Security.Cryptography.X509Certificates.StoreName.My
                    });
                    db.SaveChanges();
                }

                if (!db.Applications.Any())
                {
                    var readScope = new Scope
                    {
                        AllowedClients = new List<Client> { CodeClient, ImplicitClient, resourceOwnerClient, client },
                        Name = "read",
                        Description = "Read data",
                        Emphasize = false
                    };

                    var searchScope = new Scope
                    {
                        AllowedClients = new List<Client> { CodeClient, resourceOwnerClient },
                        Name = "search",
                        Description = "Search data",
                        Emphasize = false
                    };

                    var writeScope = new Scope
                    {
                        AllowedClients = new List<Client> { resourceOwnerClient },
                        Name = "write",
                        Description = "write data",
                        Emphasize = true
                    };

                    var application = new Application
                    {
                        Enabled = true,
                        Name = "User management",
                        Namespace = "users",
                        Audience = "users",
                        Description = "This app manages your users",
                        LogoUrl = "http://en.opensuse.org/images/0/0b/Icon-user.png",
                        Scopes = new List<Scope> { readScope, searchScope, writeScope },
                        RequireConsent = true,
                        TokenLifetime = 60,
                        AllowRefreshToken = true,
                        SigningKey = new SymmetricKey { Name="main signing key", Value = Convert.FromBase64String("1fTiS2clmPTUlNcpwYzd5i4AEFJ2DEsd8TcUsllmaKQ=") }
                    };
                    db.Applications.Add(application);
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }