コード例 #1
0
ファイル: Startup.cs プロジェクト: zoeforever/Challenge
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpContextAccessor();
            services.AddSingleton <IUserService, UserService>();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //services.AddIdentityServer()
            //    .AddDeveloperSigningCredential()
            //    //.AddInMemoryClients(null);
            //    .AddInMemoryApiResources();

            IdentityServerClients client = new IdentityServerClients(services.BuildServiceProvider());

            services.AddIdentityServer()//Ids4服务
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(IdentityServerResources.GetApiResources())
            .AddInMemoryIdentityResources(IdentityServerResources.GetIdentityResources())
            .AddInMemoryClients(IdentityServerClients.GetClients()) //把配置文件的Client配置资源放到内存
            //.AddResourceOwnerValidator<ResourceOwnerPasswordValidator>();//自定义用户登录。即自定义用户登录又添加测试用户,则以测试用户为准
            .AddTestUsers(client.GetUsers().Result);                //添加测试用户

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options =>
            {
                options.Authority            = Configuration["JWT:Authority"];
                options.RequireHttpsMetadata = false;
                options.Audience             = "WebAppAPI";
                options.TokenValidationParameters.ClockSkew             = TimeSpan.FromMinutes(0);
                options.TokenValidationParameters.RequireExpirationTime = true;
            });
        }
コード例 #2
0
        public async Task Seed()
        {
            // create the database contexts and apply any pending migrations
            if (_context.Database.GetPendingMigrations().Any())
            {
                _context.Database.Migrate();
            }

            if (_identityServerConfigContext.Database.GetPendingMigrations().Any())
            {
                _identityServerConfigContext.Database.Migrate();
            }

            if (_identityServerPersistedGrantContext.Database.GetPendingMigrations().Any())
            {
                _identityServerPersistedGrantContext.Database.Migrate();
            }
            if ((await _roleManager.FindByNameAsync("AdminUserClassicRole")) == null)
            {
                var addedRole = new DbRole {
                    Name = "AdminUserClassicRole", Description = "classic style admin role"
                };
                var addRoleResult = await _roleManager.CreateAsync(addedRole);

                if (addRoleResult.Succeeded)
                {
                    await _roleManager.AddClaimAsync(addedRole, new Claim(ClaimTypes.Role, "AdminUSerClassicRoleClaim"));
                }
            }

            string emailUsername = "******";
            DbUser user          = await _userManager.FindByNameAsync(emailUsername);

            if (user == null)
            {
                var result = await _userManager.CreateAsync(new DbUser
                {
                    UserName         = emailUsername,
                    DateOfBirth      = new DateTime(1970, 1, 1),
                    Email            = emailUsername,
                    Firstname        = "test",
                    LockoutEnabled   = true,
                    Surname          = "user",
                    EmailConfirmed   = true,
                    TwoFactorEnabled = false
                }, "Pa$$word1");


                if (result.Succeeded)
                {
                    user = await _userManager.FindByNameAsync(emailUsername);

                    await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, MusicStoreConstants.Roles.AdminUser));

                    await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, MusicStoreConstants.Roles.TestUser));

                    await _userManager.AddClaimAsync(user, new Claim(MusicStoreConstants.CLaimTypes.MusicStoreApiReadAccess, "true"));

                    await _userManager.AddClaimAsync(user, new Claim(MusicStoreConstants.CLaimTypes.MusicStoreApiWriteAccess, "true"));

                    var addRoleResult = await _userManager.AddToRoleAsync(user, "AdminUserClassicRole");
                }
                else
                {
                    _logger.LogError("Error adding user - error: " + string.Join(", ", result.Errors.Select(e => e.Description)));
                }
            }

            if (!_identityServerConfigContext.Clients.Any())
            {
                IdentityServerConfigUrls urls = new IdentityServerConfigUrls()
                {
                    AngularAppClientUri = "https://localhost:44350",
                    MvcClientUri        = "https://localhost:44357"
                };

                string angularClientUrl = this._configuration.GetValue <string>("AngularAppClientUrl");
                if (!string.IsNullOrWhiteSpace(angularClientUrl))
                {
                    urls.AngularAppClientUri = angularClientUrl;
                }

                // set url for the server side mvc app "/samples/oauthtest"
                string mvcAppClientUrl = this._configuration.GetValue <string>("MvcAppClientUrl");
                if (!string.IsNullOrWhiteSpace(mvcAppClientUrl))
                {
                    urls.MvcClientUri = mvcAppClientUrl;
                }

                foreach (var client in IdentityServerClients.GetClients(urls))
                {
                    _identityServerConfigContext.Clients.Add(client.ToEntity());
                }
                _identityServerConfigContext.SaveChanges();
            }

            if (!_identityServerConfigContext.IdentityResources.Any())
            {
                foreach (var resource in IdentityServerResources.GetIdentityResources())
                {
                    _identityServerConfigContext.IdentityResources.Add(resource.ToEntity());
                }
                _identityServerConfigContext.SaveChanges();
            }

            if (!_identityServerConfigContext.ApiResources.Any())
            {
                foreach (var resource in IdentityServerResources.GetApiResources())
                {
                    _identityServerConfigContext.ApiResources.Add(resource.ToEntity());
                }
                _identityServerConfigContext.SaveChanges();
            }

            ContentCreator contentCreator = new ContentCreator(_context);

            if (await _context.AlbumGroups.CountAsync() == 0)
            {
                //create default groups
                await _context.AlbumGroups.AddAsync(new DbAlbumGroup
                {
                    Key        = "FEATURED_ALBUMS",
                    Name       = "Featured albums",
                    CreatedUtc = DateTime.UtcNow,
                    UpdatedUtc = DateTime.UtcNow
                });

                await _context.AlbumGroups.AddAsync(new DbAlbumGroup
                {
                    Key        = "NEW_ALBUMS",
                    Name       = "New albums",
                    CreatedUtc = DateTime.UtcNow,
                    UpdatedUtc = DateTime.UtcNow
                });

                await _context.AlbumGroups.AddAsync(new DbAlbumGroup
                {
                    Key        = "BESTSELLING_ALBUMS",
                    Name       = "Bestselling albums",
                    CreatedUtc = DateTime.UtcNow,
                    UpdatedUtc = DateTime.UtcNow
                });

                await _context.SaveChangesAsync();
            }

            if (await _context.Genres.CountAsync() == 0)
            {
                await contentCreator.CreateGenres("Rock", "Pop", "Indie", "Funk", "Grunge", "Electronic", "Punk", "Alternative");
            }

            if (await _context.Artists.CountAsync() == 0)
            {
                await contentCreator.CreateSeedContent();
            }
        }