示例#1
0
 public ApiResourcesController(ConfigurationDbContext context)
 {
     this._context = context;
 }
示例#2
0
        public static async Task EnsureSeedDataAsync(PersistedGrantDbContext grantContext, ConfigurationDbContext configContext)
        {
            grantContext.Database.Migrate();
            configContext.Database.Migrate();

            if (!configContext.Clients.Any())
            {
                foreach (var client in Config.GetClients().ToList())
                {
                    configContext.Clients.Add(client.ToEntity());
                }
            }

            if (!configContext.IdentityResources.Any())
            {
                foreach (var resource in Config.GetIdentityResources().ToList())
                {
                    configContext.IdentityResources.Add(resource.ToEntity());
                }
            }

            if (!configContext.ApiResources.Any())
            {
                foreach (var resource in Config.GetApis().ToList())
                {
                    configContext.ApiResources.Add(resource.ToEntity());
                }
            }

            await configContext.SaveChangesAsync();
        }
示例#3
0
        private static void InitializeIdentity(ConfigurationDbContext configurationDbContext, IConfiguration configuration)
        {
            string defaultClientAuthority = configuration[$"Identity:DefaultClient:Authority"];

            if (string.IsNullOrEmpty(defaultClientAuthority))
            {
                throw new Exception("Identity default client authority string is empty");
            }

            string defaultClientId = configuration[$"Identity:DefaultClient:ClientId"];

            if (string.IsNullOrEmpty(defaultClientId))
            {
                throw new Exception("Identity default client ID is empty");
            }

            string defaultClientName = configuration[$"Identity:DefaultClient:ClientName"];

            if (string.IsNullOrEmpty(defaultClientName))
            {
                throw new Exception("Identity default client name is empty");
            }

            string defaultClientLogoUrl = configuration[$"Identity:DefaultClient:ClientLogoUrl"];

            if (string.IsNullOrEmpty(defaultClientLogoUrl))
            {
                throw new Exception("Identity default client logo URL is empty");
            }

            string defaultClientSecret = configuration[$"Identity:DefaultClient:ClientSecret"];

            if (string.IsNullOrEmpty(defaultClientSecret))
            {
                throw new Exception("Identity default client secret is empty");
            }

            string apiResources = configuration["Identity:ApiResources"];

            if (string.IsNullOrEmpty(apiResources))
            {
                throw new Exception("Identity API resources are empty");
            }

            string[] apiResourcesSplit = apiResources.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            if (apiResourcesSplit.Length == 0)
            {
                throw new Exception("Identity API resources are empty");
            }

            List <string> scopes = new List <string>();

            scopes.Add(IdentityServerConstants.StandardScopes.OpenId);
            scopes.Add(IdentityServerConstants.StandardScopes.Profile);
            scopes.Add(IdentityServerConstants.StandardScopes.Email);
            scopes.Add(IdentityServerConstants.StandardScopes.OfflineAccess);

            List <ApiResource> apiResourcesList = new List <ApiResource>();

            for (int i = 0; i < apiResourcesSplit.Length; i++)
            {
                scopes.Add(apiResourcesSplit[i]);

                string apiResourceName = configuration[$"Identity:ApiResourceDetails:{apiResourcesSplit[i]}:Name"];
                if (string.IsNullOrEmpty(apiResourceName))
                {
                    throw new Exception($"Identity API resource name for API resource {apiResourcesSplit[i]} is empty");
                }

                apiResourcesList.Add(new ApiResource(apiResourcesSplit[i], apiResourceName, new string[] { IdentityCoreConstants.DeveloperAdminClaim }));
            }

            var defaultClient = new Client
            {
                ClientId   = defaultClientId,
                ClientName = defaultClientName,
                LogoUri    = defaultClientLogoUrl,
                AbsoluteRefreshTokenLifetime = Int32.MaxValue,
                AllowAccessTokensViaBrowser  = true,
                AlwaysSendClientClaims       = true,
                IncludeJwtId           = true,
                RefreshTokenExpiration = TokenExpiration.Sliding,
                AllowedGrantTypes      = GrantTypes.Code,
                AllowedScopes          = scopes,
                AllowOfflineAccess     = true,
                RequireConsent         = false,
                ClientSecrets          =
                {
                    new Secret(defaultClientSecret.Sha256())
                },
                RedirectUris =
                {
                    $"{defaultClientAuthority}signin-oidc"
                },
                PostLogoutRedirectUris =
                {
                    $"{defaultClientAuthority}",
                    $"{defaultClientAuthority}signout-callback-oidc"
                }
            };

            if (!configurationDbContext.Clients.Any())
            {
                Console.WriteLine("Clients are being populated...");

                configurationDbContext.Clients.Add(defaultClient.ToEntity());

                configurationDbContext.SaveChanges();

                Console.WriteLine("Clients populated successfully");
            }

            if (!configurationDbContext.ApiResources.Any())
            {
                Console.WriteLine("API resources are being populated...");

                foreach (var apiResource in apiResourcesList)
                {
                    configurationDbContext.ApiResources.Add(apiResource.ToEntity());
                }

                configurationDbContext.SaveChanges();

                Console.WriteLine("API resources populated successfully");
            }

            if (!configurationDbContext.IdentityResources.Any())
            {
                Console.WriteLine("Identity resources are being populated...");

                configurationDbContext.IdentityResources.Add(new IdentityResources.OpenId().ToEntity());
                configurationDbContext.IdentityResources.Add(new IdentityResources.Profile().ToEntity());
                configurationDbContext.IdentityResources.Add(new IdentityResources.Email().ToEntity());
                configurationDbContext.IdentityResources.Add(new IdentityResources.Phone().ToEntity());

                configurationDbContext.SaveChanges();

                Console.WriteLine("Identity resources populated successfully");
            }
        }
示例#4
0
 public AppProvider(ConfigurationDbContext configurationDbContext)
 {
     _configurationDbContext = configurationDbContext;
 }
        static void Data_Seeding_Users(
            UserDbContext userContext,
            TenantDbContext tenantDbContext,
            UserManager <AppUser> userManager,
            ConfigurationDbContext identityserverDbContext,
            IdentityServer4MicroServiceOptions options)
        {
            if (!userContext.Roles.Any())
            {
                var roles = typeof(DefaultRoles).GetFields();

                foreach (var role in roles)
                {
                    var roleName = role.GetRawConstantValue().ToString();

                    var roleDisplayName = role.GetCustomAttribute <DisplayNameAttribute>().DisplayName;

                    userContext.Roles.Add(new AppRole
                    {
                        Name             = roleName,
                        NormalizedName   = roleDisplayName,
                        ConcurrencyStamp = Guid.NewGuid().ToString()
                    });
                }

                userContext.SaveChanges();
            }

            if (!userContext.Users.Any())
            {
                var roleIds = userContext.Roles.Select(x => x.Id).ToList();

                var tenantIds = tenantDbContext.Tenants.Select(x => x.Id).ToList();

                var user = new AppUser()
                {
                    Email          = options.DefaultUserAccount,
                    UserName       = options.DefaultUserAccount,
                    PasswordHash   = options.DefaultUserPassword,
                    EmailConfirmed = true,
                    ParentUserID   = AppConstant.seedUserId
                };

                var r = AppUserService.CreateUser(AppConstant.seedTenantId,
                                                  userManager,
                                                  userContext,
                                                  user,
                                                  roleIds,
                                                  $"{AppConstant.MicroServiceName}.all",
                                                  tenantIds).Result;

                #region User Clients
                var clientIds = identityserverDbContext.Clients.Select(x => x.Id).ToList();
                foreach (var cid in clientIds)
                {
                    user.Clients.Add(new AspNetUserClient()
                    {
                        ClientId = cid
                    });
                }
                #endregion

                #region User ApiResources
                var apiIds = identityserverDbContext.ApiResources.Select(x => x.Id).ToList();
                foreach (var apiId in apiIds)
                {
                    user.ApiResources.Add(new AspNetUserApiResource()
                    {
                        ApiResourceId = apiId,
                    });
                }
                #endregion

                userContext.SaveChanges();
            }
        }
示例#6
0
 public ManageIdentityResourcesController(ConfigurationDbContext configurationContext, IMemoryCache memoryCache)
 {
     this._configurationContext = configurationContext;
     this._cache = memoryCache;
 }
示例#7
0
        internal static async Task SeedClients(ConfigurationDbContext configurationDbContext)
        {
            await configurationDbContext.Clients.AddRangeAsync(new List <Client>
            {
                new Client
                {
                    ClientId          = "t8agr5xKt4$3sad31oj$d",
                    ClientName        = "Expense Tracker Web Api",
                    AllowedGrantTypes = new List <ClientGrantType>
                    {
                        new ClientGrantType
                        {
                            GrantType = ResourceOwnerPassword
                        },
                        new ClientGrantType
                        {
                            GrantType = ClientCredentials
                        }
                    },
                    AllowOfflineAccess = true,
                    ClientSecrets      = new List <ClientSecret>
                    {
                        new ClientSecret
                        {
                            Value = "234edf$43-fs$a4asdf-423qwadsaes$f-34$5f$-web-api".ToSha256()
                        }
                    },
                    RequireClientSecret = true,
                    AlwaysIncludeUserClaimsInIdToken = true,
                    AllowedScopes = new List <ClientScope>
                    {
                        new ClientScope
                        {
                            Scope = "app.expensetracker.api.full"
                        },

                        new ClientScope
                        {
                            Scope = "app.expensetracker.api.read"
                        },

                        new ClientScope
                        {
                            Scope = "app.expensetracker.api.write"
                        },

                        new ClientScope
                        {
                            Scope = "openid"
                        },

                        new ClientScope
                        {
                            Scope = "offline_access"
                        },

                        new ClientScope
                        {
                            Scope = "profile"
                        }
                    }
                },

                new Client
                {
                    ClientId          = "t8agr5xKt4$3",
                    ClientName        = "Expense Tracker Swagger",
                    AllowedGrantTypes = new List <ClientGrantType>
                    {
                        new ClientGrantType
                        {
                            GrantType = ClientCredentials
                        }
                    },
                    ClientSecrets = new List <ClientSecret>
                    {
                        new ClientSecret
                        {
                            Value = "234edf$43-fs$a34asdf-423qwadsaes$f-34$5f$-swagger".ToSha256()
                        }
                    },
                    RequireClientSecret = true,
                    AllowedScopes       = new List <ClientScope>
                    {
                        new ClientScope
                        {
                            Scope = "app.expensetracker.api.full"
                        },

                        new ClientScope
                        {
                            Scope = "app.expensetracker.api.read"
                        },

                        new ClientScope
                        {
                            Scope = "app.expensetracker.api.write"
                        },
                    }
                }
            });
        }
 public EntityFrameworkApiResourceWriter(ConfigurationDbContext context)
 {
     this.context = context ?? throw new ArgumentNullException(nameof(context));
 }
示例#9
0
 public PoliciesController(ConfigurationDbContext context)
 {
     _context = context;
 }
 public ClientService(ConfigurationDbContext context)
 {
     _context = context;
 }
示例#11
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="mapper">The mapper.</param>
 /// <param name="configDb">The configuration db context.</param>
 /// <param name="appConfig">The app config.</param>
 public ClientRepository(ConfigurationDbContext configDb, IMapper mapper, AppConfig appConfig)
 {
     this.configDb  = configDb;
     this.mapper    = mapper;
     this.appConfig = appConfig;
 }
示例#12
0
        public static void Initialize(IdDbContext context,
                                      RoleManager <Role> roleManager,
                                      ConfigurationDbContext configurationDbContext,
                                      PersistedGrantDbContext persistedGrantDbContext)
        {
            /* How to:
             * First generate the migration IF THERE IS A CHANGE IN THE MODEL,
             * if what its needed it just seeding the database generate a new migration
             * is not something to do.
             *
             * Second just start the server. That will migrate the database if it is needed
             * and will seed the database.
             *
             * in production with many instances running this type of code can cause
             * problems, Read 'apply-migrations-at-runtime':
             * https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying
             *
             * THIS IS A MIGRATION AT RUNTIME
             */

            // use code with precaution
            context.Database.Migrate();
            persistedGrantDbContext.Database.Migrate(); // migrating persistedGrant(devices, devides_codes, ...) tables
            configurationDbContext.Database.Migrate();  // migrating configuration(resources, clients,...) tables

            if (!context.Roles.Any())
            {
                // seeding database
                var result = roleManager.CreateAsync(new Role
                {
                    Name           = RoleConstants.USER_ROLE,
                    NormalizedName = RoleConstants.USER_ROLE
                }).Result;

                if (!result.Succeeded)
                {
                    throw new Exception("An Error occurred when creating the DB");
                }
            }

            if (!configurationDbContext.IdentityResources.Any())
            {
                var identityResourcesApi = new List <IdentityResource>
                {
                    new IdentityResources.OpenId().ToEntity(),
                    new IdentityResources.Profile().ToEntity(),
                    new IdentityResources.Address().ToEntity(),
                    new IdentityResources.Email().ToEntity(),
                    new IdentityResources.Phone().ToEntity()
                };

                configurationDbContext.IdentityResources.AddRange(identityResourcesApi);
                configurationDbContext.SaveChanges();
            }

            if (!configurationDbContext.Clients.Any())
            {
                var firstPartyUserClient = new Client
                {
                    ClientId               = "TodoAppFirstPartyUser",
                    ClientName             = "Todo App First Party - User",
                    AllowedGrantTypes      = GrantTypes.Code,
                    RequireClientSecret    = false, // default is true
                    RequirePkce            = true,  // default is false
                    AllowPlainTextPkce     = false, // default is false
                    RequireConsent         = false, // this is a firstParty client
                    PostLogoutRedirectUris =
                    {
                        "https://todoapp-demo.azurewebsites.net"
                    },
                    AllowedScopes =
                    {
                        "TodoAppApi.TodoAppUser", // This is name of an ApiResource scope
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile
                    },
                    RedirectUris = new List <string>
                    {
                        "https://todoapp-demo.azurewebsites.net/auth/codes"
                    },
                    AllowedCorsOrigins = new List <string>
                    {
                        "https://todoapp-demo.azurewebsites.net"
                    }
                }.ToEntity();

                configurationDbContext.Clients.Add(firstPartyUserClient);
                configurationDbContext.SaveChanges();
            }

            if (!configurationDbContext.ApiResources.Any())
            {
                var apiResource = new ApiResource
                {
                    Name   = "TodoAppApi",
                    Scopes =
                    {
                        new Scope
                        {
                            Name        = "TodoAppApi.TodoApp",
                            DisplayName = "Full access to TodoApp",
                            // check UserProfileService
                            UserClaims = new List <string>{
                                "preferred_username"
                            }
                        },
                        new Scope
                        {
                            Name        = "TodoAppApi.TodoAppUser",
                            DisplayName = "User access TodoApp",
                            // check UserProfileService
                            UserClaims = new List <string>{
                                "preferred_username"
                            }
                        }
                    }
                }.ToEntity();

                configurationDbContext.ApiResources.Add(apiResource);
                configurationDbContext.SaveChanges();
            }
        }
 public IdentityResourceController(ConfigurationDbContext context)
 {
     _context = context;
 }
 public ApiResourceController(ConfigurationDbContext context)
 {
     _context = context;
 }
 public ConfigurationDataInitializer(ConfigurationDbContext configContext, PersistedGrantDbContext prstContext)
 {
     cfgDbContext  = configContext;
     prstDbContext = prstContext;
 }
示例#16
0
 public ValuesController(ConfigurationDbContext context)
 {
     _context = context;
 }
 public SetupAppDashboardToolController(ConfigurationDbContext configContext, ILogger <SetupAppDashboardToolController> logger, AppConfig appConfig)
 {
     this.configContext = configContext;
     this.logger        = logger;
     this.appConfig     = appConfig;
 }
示例#18
0
 public PropertiesModel(ConfigurationDbContext dbContext)
 {
     _dbContext = dbContext;
 }
示例#19
0
        public static async Task EnsureSeedDataAsync(this ConfigurationDbContext context, IConfiguration configuration)
        {
            if (!context.Clients.Any())
            {
                // TODO : log:Debug "Clients being populated"

                foreach (var client in Config.GetClients(configuration)().ToList())
                {
                    await context.Clients.AddAsync(client.ToEntity());
                }

                await context.SaveChangesAsync();
            }
            else
            {
                // TODO : log:Debug "Clients already populated"
            }

            if (!context.IdentityResources.Any())
            {
                // TODO : log:Debug "IdentityResources being populated"

                foreach (var resource in Config.GetIdentityResources(configuration)().ToList())
                {
                    await context.IdentityResources.AddAsync(resource.ToEntity());
                }

                await context.SaveChangesAsync();
            }
            else
            {
                // TODO : log:Debug "IdentityResources already populated"
            }

            if (!context.ApiResources.Any())
            {
                // TODO : log:Debug "ApiResources being populated"

                foreach (var resource in Config.GetApiResources(configuration)().ToList())
                {
                    await context.ApiResources.AddAsync(resource.ToEntity());
                }

                await context.SaveChangesAsync();
            }
            else
            {
                // TODO : log:Debug "ApiResources already populated"
            }

            if (!context.ApiScopes.Any())
            {
                // TODO : log:Debug "ApiScopes being populated"

                foreach (var resource in Config.GetApiScopes(configuration)().ToList())
                {
                    await context.ApiScopes.AddAsync(resource.ToEntity());
                }

                await context.SaveChangesAsync();
            }
            else
            {
                // TODO : log:Debug "ApiScopes already populated"
            }
        }
示例#20
0
 //Inject context instance here.
 public MyClassWhereDbContextIsNeeded(ConfigurationDbContext dbContext)
 {
    this.dbContext = dbContext;
 }
示例#21
0
 public ContextInitializer(ConfigurationDbContext configurationDbContext,
                           PersistedGrantDbContext persistedGrantDbContext)
 {
     _configurationDbContext  = configurationDbContext;
     _persistedGrantDbContext = persistedGrantDbContext;
 }
示例#22
0
        public static void EnsureSeedData(IServiceProvider serviceProvider)
        {
            Console.WriteLine("Seeding database...");

            using (var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                scope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();

                {
                    ConfigurationDbContext context = scope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();

                    context.Database.Migrate();
                    EnsureSeedData(context);
                }

                {
                    UserData context = scope.ServiceProvider.GetService <UserData>();

                    context.Database.Migrate();

                    UserManager <UserModel> userMgr = scope.ServiceProvider.GetRequiredService <UserManager <UserModel> >();
                    UserModel alice = userMgr.FindByNameAsync("alice").Result;

                    if (alice == null)
                    {
                        alice = new UserModel
                        {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            EmailConfirmed = true
                        };

                        IdentityResult result = userMgr.CreateAsync(alice, "Pass123$").Result;

                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }

                        result = userMgr.AddClaimsAsync(alice, new Claim[]
                        {
                            new Claim(JwtClaimTypes.Name, "Alice Smith"),
                            new Claim(JwtClaimTypes.GivenName, "Alice"),
                            new Claim(JwtClaimTypes.FamilyName, "Smith"),
                            new Claim(JwtClaimTypes.Email, "*****@*****.**"),
                            new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                            new Claim(JwtClaimTypes.WebSite, "http://alice.my.domain"),
                            new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json),
                            new Claim("location", "Support")
                        }).Result;

                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }

                        Console.WriteLine("alice created");
                    }
                    else
                    {
                        Console.WriteLine("alice already exists");
                    }

                    UserModel frank = userMgr.FindByNameAsync("frank").Result;

                    if (frank == null)
                    {
                        frank = new UserModel
                        {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            EmailConfirmed = true
                        };

                        IdentityResult result = userMgr.CreateAsync(frank, "Pass123$").Result;

                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }

                        result = userMgr.AddClaimsAsync(frank, new Claim[]
                        {
                            new Claim(JwtClaimTypes.Name, "Frank Smith"),
                            new Claim(JwtClaimTypes.GivenName, "Frank"),
                            new Claim(JwtClaimTypes.FamilyName, "Smith"),
                            new Claim(JwtClaimTypes.Email, "*****@*****.**"),
                            new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                            new Claim(JwtClaimTypes.WebSite, "http://frank.my.domain"),
                            new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json),
                            new Claim("location", "Pioneer")
                        }).Result;

                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }

                        Console.WriteLine("frank created");
                    }
                    else
                    {
                        Console.WriteLine("frank already exists");
                    }

                    UserModel kellsy = userMgr.FindByNameAsync("mkellsy").Result;

                    if (kellsy == null)
                    {
                        kellsy = new UserModel
                        {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            EmailConfirmed = true
                        };

                        IdentityResult result = userMgr.CreateAsync(kellsy, "#1 Marvin").Result;

                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }

                        result = userMgr.AddClaimsAsync(kellsy, new Claim[]
                        {
                            new Claim(JwtClaimTypes.Name, "Michael Kellsy"),
                            new Claim(JwtClaimTypes.GivenName, "Michael"),
                            new Claim(JwtClaimTypes.FamilyName, "Kellsy"),
                            new Claim(JwtClaimTypes.Email, "*****@*****.**"),
                            new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                            new Claim(JwtClaimTypes.WebSite, "https://fofxsoft.com"),
                            new Claim(JwtClaimTypes.Address, @"{ 'street_address': '3632 Rockaway St', 'city': 'Fort Collins', 'state': 'Colorado', 'postal_code': 80526, 'country': 'USA' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json),
                            new Claim("location", "Support"),
                            new Claim("location", "Pioneer")
                        }).Result;

                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }

                        Console.WriteLine("mkellsy created");
                    }
                    else
                    {
                        Console.WriteLine("mkellsy already exists");
                    }
                }
            }

            Console.WriteLine("Done seeding database.");
            Console.WriteLine();
        }
 public ClientsController(ConfigurationDbContext context)
 {
     _context = context;
 }
示例#24
0
 public PermissionsController(ConfigurationDbContext context)
 {
     _context = context;
 }
 public ClientRepository(ConfigurationDbContext context)
 {
     _context = context;
 }
示例#26
0
 public TestController(ConfigurationDbContext Context)
 {
     this.context = Context;
 }
示例#27
0
        public async Task SeedAsync(ConfigurationDbContext context, IConfiguration configuration)
        {
            //callbacks urls from config:
            var clientUrls = new Dictionary <string, string>();

            clientUrls.Add("Mvc", configuration.GetValue <string>("MvcClient"));
            //clientUrls.Add("Spa", configuration.GetValue<string>("SpaClient"));
            //clientUrls.Add("Xamarin", configuration.GetValue<string>("XamarinCallback"));
            //clientUrls.Add("LocationsApi", configuration.GetValue<string>("LocationApiClient"));
            //clientUrls.Add("MarketingApi", configuration.GetValue<string>("MarketingApiClient"));
            //clientUrls.Add("BasketApi", configuration.GetValue<string>("BasketApiClient"));
            //clientUrls.Add("OrderingApi", configuration.GetValue<string>("OrderingApiClient"));
            //clientUrls.Add("MobileShoppingAgg", configuration.GetValue<string>("MobileShoppingAggClient"));
            //clientUrls.Add("WebShoppingAgg", configuration.GetValue<string>("WebShoppingAggClient"));

            if (!context.Clients.Any())
            {
                foreach (var client in Config.GetClients(clientUrls))
                {
                    context.Clients.Add(client.ToEntity());
                }
                await context.SaveChangesAsync();
            }
            // Checking always for old redirects to fix existing deployments
            // to use new swagger-ui redirect uri as of v3.0.0
            // There should be no problem for new ones
            // ref: https://github.com/dotnet-architecture/eShopOnContainers/issues/586
            else
            {
                List <ClientRedirectUri> oldRedirects = (await context.Clients.Include(c => c.RedirectUris).ToListAsync())
                                                        .SelectMany(c => c.RedirectUris)
                                                        .Where(ru => ru.RedirectUri.EndsWith("/o2c.html"))
                                                        .ToList();

                if (oldRedirects.Any())
                {
                    foreach (var ru in oldRedirects)
                    {
                        ru.RedirectUri = ru.RedirectUri.Replace("/o2c.html", "/oauth2-redirect.html");
                        context.Update(ru.Client);
                    }
                    await context.SaveChangesAsync();
                }
            }

            if (!context.IdentityResources.Any())
            {
                foreach (var resource in Config.GetResources())
                {
                    context.IdentityResources.Add(resource.ToEntity());
                }
                await context.SaveChangesAsync();
            }

            if (!context.ApiResources.Any())
            {
                foreach (var api in Config.GetApis())
                {
                    context.ApiResources.Add(api.ToEntity());
                }

                await context.SaveChangesAsync();
            }
        }
        public async Task SeedAsync(ConfigurationDbContext context, IConfiguration configuration)
        {
            //callbacks urls from config:
            var clientUrls = new Dictionary <string, string>();

            clientUrls.Add("Spa", configuration.GetValue <string>("SpaClient"));
            clientUrls.Add("ScoreApi", configuration.GetValue <string>("ScoreApi"));

            /// Delete all clients and repopulated, to make dev process easier
            var clientsToDelete = context.Clients;

            foreach (var client in clientsToDelete)
            {
                context.Remove(client);
                await context.SaveChangesAsync();
            }

            /// Delete all IdentityResources and repopulated, to make dev process easier
            var identityResourcesToDelete = context.IdentityResources;

            foreach (var identityResource in identityResourcesToDelete)
            {
                context.Remove(identityResource);
                await context.SaveChangesAsync();
            }

            /// Delete all ApiResources and repopulated, to make dev process easier
            var apiResourcesToDelete = context.ApiResources;

            foreach (var apiResource in apiResourcesToDelete)
            {
                context.Remove(apiResource);
                await context.SaveChangesAsync();
            }

            /// Populate all resources and clients
            if (!context.Clients.Any())
            {
                foreach (var client in Config.GetClients(clientUrls))
                {
                    await context.Clients.AddAsync(client.ToEntity());
                }
                await context.SaveChangesAsync();
            }

            if (!context.IdentityResources.Any())
            {
                foreach (var resource in Config.GetResources())
                {
                    await context.IdentityResources.AddAsync(resource.ToEntity());
                }
                await context.SaveChangesAsync();
            }

            if (!context.ApiResources.Any())
            {
                foreach (var api in Config.GetApis())
                {
                    await context.ApiResources.AddAsync(api.ToEntity());
                }

                await context.SaveChangesAsync();
            }
        }
示例#29
0
 public CommonJsonController(ConfigurationDbContext db, RoleManager <ApplicationRole> roleManager)
 {
     _db          = db;
     _roleMangeer = roleManager;
 }
示例#30
0
 public IdentityRoleRepository(ConfigurationDbContext context)
 {
     _context = context;
 }