Exemplo n.º 1
0
 public static void Performseed(ConfigurationDbContext context)
 {
     if (!context.Clients.Any())
     {
         foreach (var client in IdentityServerConfiguration.GetClients())
         {
             context.Clients.Add(client.ToEntity());
         }
         context.SaveChanges();
     }
     if (!context.IdentityResources.Any())
     {
         foreach (var resource in IdentityServerConfiguration.GetIdentityResources())
         {
             context.IdentityResources.Add(resource.ToEntity());
         }
         context.SaveChanges();
     }
     if (!context.ApiResources.Any())
     {
         foreach (var api in IdentityServerConfiguration.GetApiResources())
         {
             context.ApiResources.Add(api.ToEntity());
         }
         context.SaveChanges();
     }
 }
Exemplo n.º 2
0
        public IActionResult GetClientRequestParameters([FromRoute] string clientId)
        {
            var parameters = new Dictionary <string, string>();
            var client     = IdentityServerConfiguration.Clients(Configuration).Single(c => c.ClientId == clientId);

            if (client == null)
            {
                return(NotFound("No client was found with client ID."));
            }
            string responseType = GetResponseType(client.AllowedGrantTypes);

            if (responseType == null)
            {
                responseType = "";
            }

            parameters.Add("authority", HttpContext.GetIdentityServerIssuerUri());
            parameters.Add("client_id", clientId);
            parameters.Add("redirect_uri", client.RedirectUris.First());
            parameters.Add("post_logout_redirect_uri", client.PostLogoutRedirectUris.First());
            parameters.Add("response_type", responseType);
            parameters.Add("scope", string.Join(" ", client.AllowedScopes));

            return(Ok(parameters));
        }
Exemplo n.º 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration.GetConnectionString("DefaultConnection");

            services.AddGrpc();
            services.AddControllers();
            services.AddRazorPages();

            services.AddSwagger();
            services.AddMonitoring(builder => builder.AddNpgSql(connectionString));

            services.AddDbContext(connectionString);

            services.AddDefaultIdentity <User>()
            .AddRoles <Role>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddLocalApiAuthentication();

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
                options.UserInteraction.ErrorUrl      = "/Error";
            })
            .AddInMemoryIdentityResources(IdentityServerConfiguration.IdentityResources)
            .AddInMemoryApiResources(IdentityServerConfiguration.ApiResources)
            .AddInMemoryApiScopes(IdentityServerConfiguration.ApiScopes)
            .AddInMemoryClients(IdentityServerConfiguration.Clients(Configuration))
            .AddAspNetIdentity <User>()
            .AddDeveloperSigningCredential();     // not recommended for production - you need to store your key material somewhere secure
        }
Exemplo n.º 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddCors();
            services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();

            OidcConfiguration oidcConfiguration = IdentityServerConfiguration.GetOidcConfiguration();

            services.AddAuthentication(Constant.AuthenticationHeaderPrefix)
            .AddIdentityServerAuthentication(opt =>
            {
                opt.Authority            = "http://localhost:5000";
                opt.RequireHttpsMetadata = false;
                opt.RoleClaimType        = "role";
                opt.ApiName = "breadshop";
            });

            DbContextOptions <BreadShopDatabaseContext> options =
                new DbContextOptionsBuilder <BreadShopDatabaseContext>()
                .UseInMemoryDatabase(databaseName: "BreadShopDatabase")
                .Options;

            services.AddSingleton(options).AddScoped <BreadShopDatabaseContext>();

            services.AddScoped <IProductRepository, ProductRepository>();
            services.AddScoped <IProductApplicationService, ProductApplicationService>();
            services.AddScoped <IStockRepository, StockRepository>();
            services.AddScoped <IStockApplicationService, StockApplicationService>();
        }
Exemplo n.º 5
0
        private static void InitializeIdentityServer(IServiceProvider provider)
        {
            var context = provider.GetRequiredService <ConfigurationDbContext>();

            if (!context.Clients.Any())
            {
                foreach (var client in IdentityServerConfiguration.GetClients())
                {
                    context.Clients.Add(client.ToEntity());
                }
                context.SaveChanges();
            }

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

            if (!context.ApiResources.Any())
            {
                foreach (var resource in IdentityServerConfiguration.GetApis())
                {
                    context.ApiResources.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }
        }
Exemplo n.º 6
0
 public AccountController(AccountOrchestrator accountOrchestrator, IOwinWrapper owinWrapper, IdentityServerConfiguration identityServerConfiguration, ILogger logger)
 {
     _accountOrchestrator         = accountOrchestrator;
     _owinWrapper                 = owinWrapper;
     _identityServerConfiguration = identityServerConfiguration;
     _logger = logger;
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            var cors = new DefaultCorsPolicyService(new Logger <DefaultCorsPolicyService>(new LoggerFactory()))
            {
                AllowAll = true
            };

            services.AddSingleton <ICorsPolicyService>(cors);
            var connectionString = Configuration["ConnectionStrings:DBConnection"];

            //Begin Identity Configuration
            services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(connectionString));
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddMvc();
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(IdentityServerConfiguration.ApiResources())
            .AddInMemoryClients(IdentityServerConfiguration.Clients())
            .AddInMemoryIdentityResources(IdentityServerConfiguration.IdentityResources())
            .AddTestUsers(TestUsers.GetUsers());

            //End Identity Configuration
            var container = new WindsorContainer();

            Bootstrapper.WireUp(container);

            UserManagementBootstrapper.Wireup(container, connectionString);
            var service = new WindsorServiceResolver(services, container).GetServiceProvider();

            return(service);
        }
        private static void EnsureSeedData(ConfigurationDbContext context)
        {
            if (!context.Clients.Any())
            {
                foreach (var client in IdentityServerConfiguration.GetClientScope().ToList())
                {
                    context.Clients.Add(client.ToEntity());
                }
                context.SaveChanges();
            }


            if (!context.IdentityResources.Any())
            {
                foreach (var resource in IdentityServerConfiguration.GetIdentityResources().ToList())
                {
                    context.IdentityResources.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }

            if (!context.ApiResources.Any())
            {
                foreach (var resource in IdentityServerConfiguration.GetApiResources().ToList())
                {
                    context.ApiResources.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }
        }
Exemplo n.º 9
0
        public async Task <IActionResult> Seed()
        {
            _logger.LogInformation("Start seeding database");

            if (_configurationDbContext.Clients.Any())
            {
                return(Ok());
            }

            var clients          = IdentityServerConfiguration.Clients(_configuration);
            var identityResource = IdentityServerConfiguration.IdentityResources;
            var apiResources     = IdentityServerConfiguration.ApiResources;

            await _configurationDbContext.Clients.AddRangeAsync(clients.Select(s => s.ToEntity()));

            await _configurationDbContext.IdentityResources.AddRangeAsync(identityResource.Select(s => s.ToEntity()));

            await _configurationDbContext.ApiResources.AddRangeAsync(apiResources.Select(s => s.ToEntity()));

            await _configurationDbContext.SaveChangesAsync();

            _logger.LogInformation("Seeding database successful");

            return(Ok());
        }
Exemplo n.º 10
0
        public override void Arrange()
        {
            base.Arrange();


            AddUserToContext("USER_ID", LoggedInEmail);

            _accountOrchestrator = new Mock <AccountOrchestrator>();
            _owinWrapper         = new Mock <IOwinWrapper>();

            var identityServerConfiguration = new IdentityServerConfiguration {
                EmployerPortalUrl = EmployerPortalUrl
            };

            _configurationService = new Mock <IConfigurationService>();
            _configurationService.Setup(s => s.GetAsync <EmployerUsersConfiguration>()).Returns(Task.FromResult(
                                                                                                    new EmployerUsersConfiguration
            {
                Account = new AccountConfiguration
                {
                    UnlockCodeLength = UnlockCodeLength
                }
            }));

            _accountController = new AccountController(_accountOrchestrator.Object, _owinWrapper.Object, identityServerConfiguration, _logger.Object);
            _accountOrchestrator.Setup(x => x.UnlockUser(It.IsAny <UnlockUserViewModel>())).ReturnsAsync(new OrchestratorResponse <UnlockUserViewModel>()
            {
                Data = new UnlockUserViewModel {
                    ErrorDictionary = new Dictionary <string, string>()
                }
            });
            _accountOrchestrator.Setup(x => x.GetUnlockCodeLength()).ReturnsAsync(UnlockCodeLength);

            _accountController.ControllerContext = _controllerContext.Object;
        }
        internal static IEnumerable <Client> GetClients(IdentityServerConfiguration identityServerConfig, IList <string> microservices)
        {
            microservices.Add(IdentityServerConstants.StandardScopes.OpenId);
            microservices.Add(IdentityServerConstants.StandardScopes.Profile);
            microservices.Add(IdentityServerConstants.StandardScopes.OfflineAccess);

            return(new List <Client>()
            {
                new Client
                {
                    ClientName = "Microservices",
                    ClientId = identityServerConfig.ClientId,
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                    AllowedScopes = microservices,
                    ClientSecrets =
                    {
                        new Secret(identityServerConfig.ClientSecret.Sha256())
                    },
                    AllowOfflineAccess = true,
                    AccessTokenType = AccessTokenType.Jwt,
                    AccessTokenLifetime = 900, //Seconds
                    RequireConsent = false
                }
            });
        }
        public void Initialize()
        {
            if (!_configDbContext.Clients.Any())
            {
                foreach (var client in IdentityServerConfiguration.GetClients().ToList())
                {
                    _configDbContext.Clients.Add(client.ToEntity());
                }
                _configDbContext.SaveChanges();
            }


            if (!_configDbContext.IdentityResources.Any())
            {
                foreach (var resource in IdentityServerConfiguration.GetIdentityResources().ToList())
                {
                    _configDbContext.IdentityResources.Add(resource.ToEntity());
                }
                _configDbContext.SaveChanges();
            }

            if (!_configDbContext.ApiResources.Any())
            {
                foreach (var resource in IdentityServerConfiguration.GetApiResources().ToList())
                {
                    _configDbContext.ApiResources.Add(resource.ToEntity());
                }
                _configDbContext.SaveChanges();
            }
        }
Exemplo n.º 13
0
        private List <Client> GetClients(IdentityServerConfiguration configuration, IRelyingPartyRepository relyingPartyRepository)
        {
            var self = new Client
            {
                ClientName     = "Das Id Manager",
                ClientId       = "idp",
                Flow           = Flows.Implicit,
                RequireConsent = false,

                RedirectUris = new List <string>
                {
                    configuration.ApplicationBaseUrl
                },
                PostLogoutRedirectUris = new List <string>
                {
                    configuration.ApplicationBaseUrl
                },
                AllowedScopes = new List <string>
                {
                    "openid", "profile"
                }
            };
            var clients = new List <Client> {
                self
            };

            var relyingParties = relyingPartyRepository.GetAllAsync().Result;

            PopulateRelyingPartyModel(relyingParties);

            clients.AddRange(relyingParties.Select(rp => new Client
            {
                ClientName    = rp.Name,
                ClientId      = rp.Id,
                Flow          = (Flows)rp.Flow,
                ClientSecrets = new List <Secret>
                {
                    new Secret(rp.ClientSecret)
                },
                RequireConsent = false,
                RedirectUris   = new List <string>
                {
                    rp.ApplicationUrl
                },
                PostLogoutRedirectUris = new List <string>
                {
                    rp.LogoutUrl
                },
                AllowedScopes = new List <string>
                {
                    "openid",
                    "profile"
                }
            }));


            return(clients);
        }
Exemplo n.º 14
0
        private void ConfigureIdentityServer(IAppBuilder app, IdentityServerConfiguration configuration, IRelyingPartyRepository relyingPartyRepository)
        {
            _logger.Debug("Setting up IdentityServer");

            AntiForgeryConfig.UniqueClaimTypeIdentifier = DasClaimTypes.Id;

            app.Map("/identity", idsrvApp =>
            {
                var factory = new IdentityServerServiceFactory()
                              .UseDasUserService()
                              .UseInMemoryClients(GetClients(configuration, relyingPartyRepository))
                              .UseInMemoryScopes(GetScopes())
                              .RegisterDasServices(StructuremapMvc.Container);
                factory.RedirectUriValidator = new Registration <IRedirectUriValidator>((dr) => new StartsWithRedirectUriValidator());

                factory.ConfigureDefaultViewService <CustomIdsViewService>(new DefaultViewServiceOptions());
                if (!ConfigurationManager.AppSettings["EnvironmentName"].Equals("LOCAL", StringComparison.CurrentCultureIgnoreCase))
                {
                    factory.AuthorizationCodeStore = new Registration <IAuthorizationCodeStore>(typeof(RedisAuthorizationCodeStore));
                }

                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    SiteName = "Digital Apprenticeship Service",

                    CspOptions = new CspOptions()
                    {
                        FontSrc  = "* data:",
                        ImgSrc   = "* data:",
                        FrameSrc = "* data:",
                        Enabled  = false
                    },
                    SigningCertificate = LoadCertificate(),
                    Endpoints          = new EndpointOptions
                    {
                        EnableCheckSessionEndpoint = false,
                    },
                    Factory = factory,

                    AuthenticationOptions = new AuthenticationOptions
                    {
                        EnablePostSignOutAutoRedirect         = false,
                        EnableAutoCallbackForFederatedSignout = true,
                        EnableSignOutPrompt = false,
                        CookieOptions       = new CookieOptions
                        {
                            AllowRememberMe   = false,
                            ExpireTimeSpan    = new TimeSpan(0, 10, 0),
                            IsPersistent      = false,
                            SecureMode        = CookieSecureMode.Always,
                            SlidingExpiration = true
                        },
                        PostSignOutAutoRedirectDelay = 0,
                        SignInMessageThreshold       = 1
                    }
                });
            });
        }
Exemplo n.º 15
0
        public static IServiceCollection AddCrazyPriceIdentityServer(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <IUserService, UserService>();
            services.AddTransient <ICryptographicService, CryptographicService>();
            services.AddScoped <IProfileService, IdentityProfileService>();

            var config = new IdentityServerConfiguration(configuration);

            services.AddCors(options =>
            {
                options.AddPolicy(config.PolicyName,
                                  policyBuilder =>
                {
                    policyBuilder
                    .AllowCredentials()
                    .WithOrigins(config.Origins)
                    .SetIsOriginAllowedToAllowWildcardSubdomains()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            var builder = services.AddIdentityServer(options =>
            {
                // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
                options.EmitStaticAudienceClaim = true;
                options.IssuerUri = config.IssuerUrl;
            })
                          .AddInMemoryIdentityResources(config.IdentityResources)
                          .AddInMemoryApiResources(config.ApiResources)
                          .AddInMemoryApiScopes(config.ApiScopes)
                          .AddInMemoryClients(config.Clients);

            services.AddAuthentication()
            .AddGoogle("Google", options =>
            {
                options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;;

                options.ClientId     = config.GoogleClientId;
                options.ClientSecret = config.GoogleClientSecret;
            })
            .AddFacebook("Facebook", options =>
            {
                options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;;

                options.ClientId     = config.FacebookClientId;
                options.ClientSecret = config.FacebookClientSecret;
            });

            builder
            .AddSigningCredential(new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                                    config.CertificateName), config.CertificatePassword));

            return(services);
        }
Exemplo n.º 16
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc();
     services.AddIdentityServer()
     .AddDeveloperSigningCredential()
     .AddInMemoryClients(IdentityServerConfiguration.GetClientScope())
     .AddInMemoryApiResources(IdentityServerConfiguration.GetApiResources())
     .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
     .AddTestUsers(IdentityServerConfiguration.GetUsers().ToList());
 }
Exemplo n.º 17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddIdentityServer()
            .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfiguration.GetApis())
            .AddInMemoryClients(IdentityServerConfiguration.GetClients())
            .AddTestUsers(IdentityServerConfiguration.GetUsers())
            .AddDeveloperSigningCredential();
        }
        private static async Task <(bool, string)> RefreshToken(HttpContext context, IdentityServerConfiguration identityServerConfiguration)
        {
            var tokenClient = new TokenClient(
                identityServerConfiguration.IdentityServerUrl + "/connect/token",
                identityServerConfiguration.ClientId,
                identityServerConfiguration.ClientSecret);

            var refreshToken = await context.GetTokenAsync(CookieAuthenticationDefaults.AuthenticationScheme, "refresh_token");

            var response = await tokenClient.RequestRefreshTokenAsync(refreshToken);

            if (response.IsError)
            {
                //logger.Warn($"Failed to refresh token for user {principal.Identity.GetUserId()}, returning 401");
                logger.LogWarning($"Failed to refresh token for user {context.User.FindFirstValue(ClaimTypes.NameIdentifier)}");

                //TODO
                //throw new HttpResponseException(HttpStatusCode.Unauthorized);

                return(false, null);
            }

            var tokens = new List <AuthenticationToken>
            {
                new AuthenticationToken {
                    Name = OpenIdConnectParameterNames.IdToken, Value = await context.GetTokenAsync(CookieAuthenticationDefaults.AuthenticationScheme, "id_token")
                },
                new AuthenticationToken {
                    Name = OpenIdConnectParameterNames.AccessToken, Value = response.AccessToken
                },
                new AuthenticationToken {
                    Name = OpenIdConnectParameterNames.RefreshToken, Value = response.RefreshToken
                }
            };
            var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(response.ExpiresIn);

            tokens.Add(new AuthenticationToken {
                Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture)
            });

            var info = await context.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            info.Properties.StoreTokens(tokens);

            //await context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, info.Principal, info.Properties);

            context.Response.OnStarting(async() =>
            {
                await context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, info.Principal, info.Properties);
            });

            return(true, response.AccessToken);
        }
Exemplo n.º 19
0
 private void ConfigureIdentityServer(IServiceCollection services, string connectionString, IConfiguration configuration)
 {
     services.AddIdentityServer(c =>
     {
         c.Endpoints = GetEndpointsOptions();
         c.Discovery = GetDiscoveryOptions();
     })
     .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
     .AddInMemoryApiResources(IdentityServerConfiguration.GetApiResources())
     .AddInMemoryClients(IdentityServerConfiguration.GetClients(BuildClientUriConfigurationDictionary(Configuration)))
     .AddAspNetIdentity <User>()
     .AddDeveloperSigningCredential();
 }
Exemplo n.º 20
0
        /// <summary>
        /// Configures the services.
        /// </summary>
        /// <param name="services">The services.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            /*services.AddIdentity<ApplicationUser, IdentityRole>()
             *  .AddEntityFrameworkStores<ApplicationDbContext>()
             *  .AddDefaultTokenProviders();*/

            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(IdentityServerConfiguration.GetApis())
            .AddInMemoryClients(IdentityServerConfiguration.GetClients());

            services.AddControllersWithViews();
        }
Exemplo n.º 21
0
        public void ConfigureServices(IServiceCollection services)
        {
            var identityServerConfig = new IdentityServerConfiguration();

            _configuration.GetSection(nameof(IdentityServerConfiguration)).Bind(identityServerConfig);

            services.AddAuthentication(config =>
            {
                config.DefaultScheme          = "Cookie";
                config.DefaultChallengeScheme = "oidc";
            })
            .AddCookie("Cookie")
            .AddOpenIdConnect("oidc", config =>
            {
                config.ClientId              = identityServerConfig.ClientId;
                config.ClientSecret          = identityServerConfig.ClientSecret;
                config.Authority             = identityServerConfig.IdentityServiceUrl;
                config.SignedOutCallbackPath = "/Books/Search";
                config.SaveTokens            = true;
                config.ResponseType          = "code";
                config.RequireHttpsMetadata  = false;
                config.Scope.Add(JwtClaimTypes.Role);
            });

            var rabbitMqConnectionString = _configuration["RabbitMqConnectionString"];

            services.AddRabbitMq(rabbitMqConnectionString);

            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfiles(new Profile[]
                {
                    new ViewModelsMapper(),
                });
            });

            IMapper mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            var apiUrl = _configuration["ApiUrl"];

            services
            .AddHttpClient("books", c => { c.BaseAddress = new Uri(apiUrl); })
            .AddTypedClient(c => RestClient.For <IBooksClient>(c));

            services.AddSignalR();
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Latest)
            .AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
        }
Exemplo n.º 22
0
 public ApplicationInitializationService(
     [NotNull] IHostingEnvironment environment,
     [NotNull] PersistedGrantDbContext persistedGrantContext,
     [NotNull] ConfigurationDbContext configurationContext,
     IOptionsSnapshot <IdentityServerConfiguration> configuration
     )
 {
     _environment           = environment ?? throw new ArgumentNullException(nameof(environment));
     _persistedGrantContext =
         persistedGrantContext ?? throw new ArgumentNullException(nameof(persistedGrantContext));
     _configurationContext =
         configurationContext ?? throw new ArgumentNullException(nameof(configurationContext));
     _configuration = configuration?.Value ?? throw new ArgumentNullException(nameof(configuration));
 }
Exemplo n.º 23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("AspNetIdentityConnection")));
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            RegisterClientsCors(services);

            services.AddMvc(option => option.EnableEndpointRouting = false);

            services.AddHttpContextAccessor();

            services.AddTransient <IEmailSender, EmailSender>();

            var _clientsConfiguration      = new Dictionary <string, ClientConfiguration>();
            var _apiResourcesConfiguration = new List <ApiResourceConfiguration>();

            Configuration.GetSection("ClientConfigurations").Bind(_clientsConfiguration);
            Configuration.GetSection("ApiResourceConfigurations").Bind(_apiResourcesConfiguration);

            var identityServerConfiguration = new IdentityServerConfiguration(_clientsConfiguration, _apiResourcesConfiguration);

            services.AddSingleton(identityServerConfiguration);

            var bootstrapper = new AppBootstrapper(Configuration, services);

            bootstrapper.Configure();

            services.AddAuthorization();
            services
            .AddAuthentication()
            .AddIdentityServerAuthentication("Bearer", options =>
            {
                options.Authority            = Configuration["IdentityServerEndpoints:Authority"];
                options.RequireHttpsMetadata = true;

                options.ApiName = "merp.auth.api";
            });
        }
Exemplo n.º 24
0
        public async Task Initialize()
        {
            this._context.Database.Migrate();
            this._persistedGrantContext.Database.Migrate();
            this._configContext.Database.Migrate();

            if (!this._context.Roles.Any(r => r.Name.Equals(Roles.ADMIN)) || !this._userManager.Users.Any(u => u.UserName.Equals(Roles.ADMIN)))
            {
                await this._roleManager.CreateAsync(new IdentityRole(Roles.ADMIN));

                await this._roleManager.CreateAsync(new IdentityRole(Roles.USER));

                await this._userManager.CreateAsync(new UserEntity { UserName = Roles.ADMIN, Email = ADMIN_EMAIL }, ADMIN_PASS);

                await this._userManager.AddToRoleAsync(await this._userManager.FindByNameAsync(Roles.ADMIN), Roles.ADMIN);
            }

            if (!_configContext.Clients.Any())
            {
                foreach (var client in IdentityServerConfiguration.GetClients())
                {
                    this._configContext.Clients.Add(client.ToEntity());
                }
            }

            if (!_configContext.IdentityResources.Any())
            {
                foreach (var resource in IdentityServerConfiguration.GetIdentityResources())
                {
                    this._configContext.IdentityResources.Add(resource.ToEntity());
                }
            }

            if (!_configContext.ApiResources.Any())
            {
                foreach (var resource in IdentityServerConfiguration.GetApiResources())
                {
                    this._configContext.ApiResources.Add(resource.ToEntity());
                }
            }

            await this._context.SaveChangesAsync();

            await this._configContext.SaveChangesAsync();

            await this._persistedGrantContext.SaveChangesAsync();
        }
Exemplo n.º 25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var identityServerSettings = Configuration.GetSection(IdentityServerSettings.Section)
                                         .Get <IdentityServerSettings>();

            var identityServerConfig = new IdentityServerConfiguration(identityServerSettings);

            services.Configure <AccountOptions>(e =>
            {
                e.AutomaticRedirectAfterSignOut = true;
            });

            services.Configure <ConsentOptions>(e =>
            {
                e.EnableOfflineAccess = false;
            });

            services.AddDbContext <IdentityDbContext>(options =>
                                                      options.UseSqlServer(
                                                          Configuration.GetConnectionString(ConfigurationConstants.AuthDbConnectionString)));

            services.AddIdentity <IdentityUser, IdentityRole>(e => IdentityConfiguration.ConfigureOptions(e, Configuration))
            .AddEntityFrameworkStores <IdentityDbContext>()
            .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(e =>
            {
                var controllerName = "Account";

                e.Cookie.Name      = "IdentityServer.Cookie";
                e.LoginPath        = $"/{controllerName}/Login";
                e.LogoutPath       = "/Home/Index";
                e.AccessDeniedPath = $"/{controllerName}/AccesDenied";
            });

            services.AddIdentityServer()
            .AddInMemoryClients(identityServerConfig.Clients)
            .AddInMemoryIdentityResources(identityServerConfig.IdentityResources)
            .AddInMemoryApiResources(identityServerConfig.Apis)
            .AddInMemoryApiScopes(identityServerConfig.ApiScopes)
            .AddTestUsers(IdentityServerConfiguration.TestUsers.ToList())
            .AddAspNetIdentity <IdentityUser>()
            .AddDeveloperSigningCredential();

            services.AddControllersWithViews();
        }
 public static IServiceCollection ConfigureIdentityServer(this IServiceCollection services)
 {
     services.AddIdentityServer().AddDeveloperSigningCredential()
     // this adds the operational data from DB (codes, tokens, consents)
     .AddOperationalStore(options =>
     {
         options.ConfigureDbContext = builder => builder.UseSqlServer(ConfigurationResolver.GetConfiguration().GetConnectionString("SQLServer"));
         // this enables automatic token cleanup. this is optional.
         options.EnableTokenCleanup   = true;
         options.TokenCleanupInterval = 30;     // interval in seconds
     })
     .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
     .AddInMemoryApiResources(IdentityServerConfiguration.GetApiResources())
     .AddInMemoryClients(IdentityServerConfiguration.GetClients())
     .AddAspNetIdentity <User>();
     return(services);
 }
Exemplo n.º 27
0
        private static async Task SeedIdentityServerConfigurationAsync(IConfigurationDbContext context, IConfiguration configuration)
        {
            // Seed OIDC clients from configuration
            var clients = IdentityServerConfiguration.Clients(configuration);

            foreach (var client in clients)
            {
                var clientEntity = await context.Clients.SingleOrDefaultAsync(c => c.ClientId == client.ClientId);

                if (clientEntity == null)
                {
                    context.Clients.Add(client.ToEntity());
                }
            }

            // Seed OIDC resource scopes from configuration
            var identityResources = IdentityServerConfiguration.IdentityResources;

            foreach (var identityResource in identityResources)
            {
                if (!context.IdentityResources.Any(c => c.Name == identityResource.Name))
                {
                    context.IdentityResources.Add(identityResource.ToEntity());
                }
            }

            // Seed API resource scopes from configuration
            var apiResources = IdentityServerConfiguration.ApiResources;

            foreach (var apiResource in apiResources)
            {
                if (!context.ApiResources.Any(c => c.Name == apiResource.Name))
                {
                    context.ApiResources.Add(apiResource.ToEntity());
                }
            }

            await context.SaveChangesAsync();
        }
Exemplo n.º 28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IdentityModelEventSource.ShowPII = true;
            services.AddCors();

            services.AddAuthentication();
            services.AddAuthorization();

            services.AddIdentityServer(options =>
            {
                options.UserInteraction.LoginUrl  = "/Identity/Login";
                options.UserInteraction.LogoutUrl = "/Identity/Logout";
            })
            .AddInMemoryApiResources(IdentityServerConfiguration.GetApiResources())
            .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
            .AddInMemoryClients(IdentityServerConfiguration.GetClients())
            .AddInMemoryApiScopes(IdentityServerConfiguration.GetApiScopes())
            .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>()
            .AddDeveloperSigningCredential();

            services.AddControllersWithViews();
        }
Exemplo n.º 29
0
        public override void Arrange()
        {
            base.Arrange();

            _orchestrator = new Mock <AccountOrchestrator>();
            _orchestrator.Setup(o => o.ResetPassword(It.IsAny <PasswordResetViewModel>())).ReturnsAsync(new OrchestratorResponse <PasswordResetViewModel>());

            _owinWrapper = new Mock <IOwinWrapper>();
            _owinWrapper.Setup(w => w.GetSignInMessage(Id))
            .Returns(new SignInMessage
            {
                ReturnUrl = ReturnUrl
            });
            _owinWrapper.Setup(x => x.GetIdsReturnUrl()).Returns(ReturnUrl);

            var identityServerConfiguration = new IdentityServerConfiguration {
                EmployerPortalUrl = EmployerPortalReturnUrl
            };

            _controller = new AccountController(_orchestrator.Object, _owinWrapper.Object, identityServerConfiguration, _logger.Object);
            _controller.ControllerContext = _controllerContext.Object;
        }
Exemplo n.º 30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            NLog.LogManager.Configuration = new NLogLoggingConfiguration(Configuration.GetSection("NLog"));

            services.AddHealthChecks();
            services.AddHttpClient();
            services.AddDbContext <DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("TaskAPI")));

            var identityServerOptions = new Common.Options.IdentityServerOptions();

            Configuration.Bind("IdentityServer", identityServerOptions);

            var certificatePath = Path.Combine(Directory.GetCurrentDirectory(), identityServerOptions.CertFolder, identityServerOptions.CertFile);

            Console.WriteLine(certificatePath);

            services.AddIdentityServer()
            .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfiguration.GetApiResources(identityServerOptions.Scope))
            .AddInMemoryClients(IdentityServerConfiguration.GetClients(identityServerOptions.ClientId, identityServerOptions.ClientSecret))
            .AddResourceOwnerValidator <CustomResourceOwnerPasswordValidator>()
            .AddProfileService <CustomProfileService>()
            .AddDeveloperSigningCredential()
            /** .AddSigningCredential(new X509Certificate2(certificatePath, identityServerOptions.CertPassword)) **/
            ;

            services.AddMvcCore().AddApiExplorer();

            services
            .AddControllers()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new SnakeCaseNamingStrategy()
                };
            });
        }