public IActionResult Get()
        {
            var options = new DbContextOptions <PersistedGrantDbContext>();

            var store = new OperationalStoreOptions();

            using (var ctx = new PersistedGrantDbContext(options, store))
            {
                ctx.Add <Client>(new Client
                {
                    ClientId      = "c1",
                    ClientSecrets = new List <ClientSecret> {
                        new ClientSecret()
                        {
                            Type = "SharedSecret", Value = "secret"
                        }
                    },
                    AllowedGrantTypes = new List <ClientGrantType> {
                        new ClientGrantType {
                            GrantType = "client_id"
                        }
                    },
                    AllowedScopes = new List <ClientScope> {
                        new ClientScope {
                            Scope = "api1"
                        }
                    }
                });
                ctx.SaveChanges();
            }

            return(Ok());
        }
        /// <summary>
        /// Initialises the persisted grant database.
        /// </summary>
        /// <param name="persistedGrantDbContext">The persisted grant database context.</param>
        /// <param name="seedingType">Type of the seeding.</param>
        public static void InitialisePersistedGrantDatabase(PersistedGrantDbContext persistedGrantDbContext,
                                                            SeedingType seedingType)
        {
            Boolean isDbInitialised = false;
            Int32   retryCounter    = 0;

            while (retryCounter < 20 && !isDbInitialised)
            {
                try
                {
                    if (persistedGrantDbContext.Database.IsSqlServer())
                    {
                        persistedGrantDbContext.Database.Migrate();
                    }

                    persistedGrantDbContext.SaveChanges();

                    isDbInitialised = true;
                    break;
                }
                catch (Exception ex)
                {
                    retryCounter++;
                    Thread.Sleep(10000);
                }
            }

            if (!isDbInitialised)
            {
                String connString = persistedGrantDbContext.Database.GetDbConnection().ConnectionString;

                Exception newException = new Exception($"Error initialising Db with Connection String [{connString}]");
                throw newException;
            }
        }
Пример #3
0
        private static void CreateOrUpdateThePersistedGrants()
        {
            var options      = new DbContextOptions <PersistedGrantDbContext>();
            var storeOptions = new OperationalStoreOptions();

            var files = GetFiles("Database/PersistedGrants");

            foreach (var file in files)
            {
                var jToken = JToken.Parse(File.ReadAllText(file.FullName));

                try
                {
                    dynamic dynObject = ConvertJTokenToObject(jToken);

                    using (var ctx = new PersistedGrantDbContext(options, storeOptions))
                    {
                        string persistedGrantKey = dynObject.Key.ToString();
                        var    persistedGrant    = ctx.PersistedGrants
                                                   .FirstOrDefault(x => x.Key == persistedGrantKey);

                        if (persistedGrant == null)
                        {
                            persistedGrant = new Data.EntityFramework.Entities.PersistedGrant();
                            ctx.PersistedGrants.Add(persistedGrant);
                        }

                        persistedGrant.Key = dynObject.Name.ToString();

                        persistedGrant.ClientId  = dynObject.DisplayName.ToString();
                        persistedGrant.SubjectId = dynObject.SubjectId.ToString();
                        persistedGrant.Type      = dynObject.Type.ToString();
                        persistedGrant.Data      = dynObject.Data.ToString();

                        persistedGrant.CreationTime = DateTime.Now;
                        persistedGrant.Expiration   = StringExtensions.ToDateTimeSafe(dynObject.Expiration.ToString());

                        ctx.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }
 public void Add(PersistedGrant persistedGrant)
 {
     context.PersistedGrants.Add(persistedGrant);
     context.SaveChanges();
 }
Пример #5
0
        public void InitializeStores()
        {
            // Cleanup
            // HACK: the memory db survives server dispose so i have to cleanup it here
            //       cannot run this tests in parallel
            _configurationDbContext.Clients.Clear();
            _configurationDbContext.IdentityResources.Clear();
            _configurationDbContext.ApiResources.Clear();
            _configurationDbContext.SaveChanges();
            _persistedGrantDbContext.PersistedGrants.Clear();
            _persistedGrantDbContext.SaveChanges();
            _defaultDbContext.UserAccounts.Clear();
            _defaultDbContext.ExternalAccounts.Clear();
            _defaultDbContext.UserAccountClaims.Clear();
            _defaultDbContext.SaveChanges();

            // Add default sample data clients
            foreach (var client in Clients.Get().ToList())
            {
                _configurationDbContext.Clients.Add(client.ToEntity());
            }
            _configurationDbContext.SaveChanges();

            foreach (var resource in Resources.GetIdentityResources().ToList())
            {
                _configurationDbContext.IdentityResources.Add(resource.ToEntity());
            }
            _configurationDbContext.SaveChanges();

            foreach (var resource in Resources.GetApiResources().ToList())
            {
                _configurationDbContext.ApiResources.Add(resource.ToEntity());
            }
            _configurationDbContext.SaveChanges();

            // Add test user accounts
            var now          = DateTime.UtcNow;
            var userAccounts = new List <UserAccount>
            {
                // Active user account with local account but no external accounts
                new UserAccount
                {
                    Id              = Guid.Parse("0c2954d2-4c73-44e3-b0f2-c00403e4adef"),
                    Email           = "alice@localhost",
                    PasswordHash    = _crypto.HashPassword("alice@localhost", _applicationOptions.PasswordHashingIterationCount),
                    CreatedAt       = now,
                    UpdatedAt       = now,
                    IsEmailVerified = true,
                    EmailVerifiedAt = now,
                    IsLoginAllowed  = true,
                    Claims          = this.CreateClaims("Alice Smith", "Alice", "Smith")
                },

                // Inactive user account with local account but no external accounts
                new UserAccount
                {
                    Id              = Guid.Parse("6b13d17c-55a6-482e-96b9-dc784015f927"),
                    Email           = "jim@localhost",
                    PasswordHash    = _crypto.HashPassword("jim@localhost", _applicationOptions.PasswordHashingIterationCount),
                    CreatedAt       = now,
                    UpdatedAt       = now,
                    IsEmailVerified = true,
                    EmailVerifiedAt = now,
                    IsLoginAllowed  = false,
                    Claims          = this.CreateClaims("Jim Panse", "Jim", "Panse"),
                },

                // Not verified user account with local account but no external accounts
                new UserAccount
                {
                    Id              = Guid.Parse("13808d08-b1c0-4f28-8d3e-8c9a4051efcb"),
                    Email           = "paul@localhost",
                    PasswordHash    = _crypto.HashPassword("paul@localhost", _applicationOptions.PasswordHashingIterationCount),
                    CreatedAt       = now,
                    UpdatedAt       = now,
                    IsEmailVerified = false,
                    IsLoginAllowed  = false,
                    Claims          = this.CreateClaims("Paul Panzer", "Paul", "Panzer")
                                      // TODO: set VerificationKey, VerificationPurpose, VerificationKeySentAt
                },

                // External user account
                new UserAccount
                {
                    Id              = Guid.Parse("58631b04-9be5-454a-aa1d-f679cd454fa6"),
                    Email           = "bob@localhost",
                    CreatedAt       = now,
                    UpdatedAt       = now,
                    IsEmailVerified = false, // had never confirmed the email, since he got via facebook
                    IsLoginAllowed  = true,  // is allowed to login since he registed via facebook
                    Claims          = this.CreateClaims("Bob Smith", "Bob", "Smith"),
                    Accounts        = new List <ExternalAccount>()
                    {
                        new ExternalAccount
                        {
                            CreatedAt = now,
                            Email     = "bob@localhost",
                            Subject   = "123456789",
                            Provider  = "facebook"
                        }
                    }
                }
            };

            // Map all references
            foreach (var userAccount in userAccounts)
            {
                foreach (var claim in userAccount.Claims)
                {
                    //claim.UserAccountId = userAccount.Id;
                    claim.UserAccount = userAccount;
                }

                if (userAccount.Accounts != null)
                {
                    foreach (var account in userAccount.Accounts)
                    {
                        account.UserAccountId = userAccount.Id;
                        account.UserAccount   = userAccount;
                    }
                }

                _defaultDbContext.UserAccounts.Add(userAccount.ToEntity());
            }

            _defaultDbContext.SaveChanges();
        }