Example #1
0
        public async Task <string> GetToken(string subjectId, string deviceId, string secret)
        {
            var request      = new TokenCreationRequest();
            var identityUser = new IdentityServerUser(subjectId);

            identityUser.DisplayName        = deviceId;
            identityUser.AuthenticationTime = System.DateTime.UtcNow;
            identityUser.IdentityProvider   = IdentityServerConstants.LocalIdentityProvider;
            request.Subject = identityUser.CreatePrincipal();
            request.IncludeAllIdentityClaims = true;
            request.ValidatedRequest         = new ValidatedRequest();
            request.ValidatedRequest.Subject = request.Subject;
            request.ValidatedRequest.SetClient(new Client()
            {
                ClientId          = deviceId,
                AllowedGrantTypes = GrantTypes.ClientCredentials,
                ClientSecrets     =
                {
                    new Secret(secret.Sha256())
                }
            });
            request.Resources = new Resources(IdentityServerConfig.GetIdentityResources(),
                                              IdentityServerConfig.GetApiResources());
            request.ValidatedRequest.Options      = _options;
            request.ValidatedRequest.ClientClaims = identityUser.AdditionalClaims;
            var token = await _tokenService.CreateAccessTokenAsync(request);

            var tokenValue = await _tokenService.CreateSecurityTokenAsync(token);

            return(tokenValue);
        }
Example #2
0
        public void ConfigureServices(IServiceCollection services)
        {
            var identityServerSettings = _config.GetSection(IdentityServerSettings.SectionName);
            var identityServerUri      = identityServerSettings.GetValue <string>(nameof(IdentityServerSettings.Uri));

            services.AddOptions();
            services.Configure <IdentityServerSettings>(identityServerSettings);

            services.AddControllers();

            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
            .AddInMemoryClients(IdentityServerConfig.GetClients());

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = identityServerUri;
                options.RequireHttpsMetadata = false;
                options.ApiName = IdentityServerConfig.MyClientId;
            });

            services.AddAuthorization();

            services.AddHttpClient();
            services.AddResponseCompression();
        }
Example #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add DB context
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

            // Add Identity
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            // Add IdentityServer
            services.AddIdentityServer(/*options =>
                                        * {
                                        * options.Events.RaiseSuccessEvents = true;
                                        * options.Events.RaiseFailureEvents = true;
                                        * options.Events.RaiseErrorEvents = true;
                                        * }*/)
            .AddTemporarySigningCredential()
            .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
            .AddInMemoryClients(IdentityServerConfig.GetClients())
            .AddAspNetIdentity <ApplicationUser>();

            // Add framework services.
            services.AddMvc();
        }
Example #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger <Startup> logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            IdentityServerConfig config = Configuration
                                          .GetSection("IdentityServer").Get <IdentityServerConfig>();

            //app.UseHttpsRedirection();

            logger.LogWarning("Variables de IS4 " + JsonConvert.SerializeObject(config));

            app.UseRouting();

            app.UseMetricServer();

            //Enviar trazas HTTP
            app.UseHttpMetrics();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Example #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string valor = Configuration.GetValue <string>("UrlApiCliente");
            ///logger.LogError("Llego UrlApiCliente " + valor);
            IdentityServerConfig config = Configuration
                                          .GetSection("IdentityServer").Get <IdentityServerConfig>();

            services.Configure <IdentityServerConfig>
                (Configuration.GetSection("IdentityServer"));

            //Usado para poder generar los Transient dinamicamente
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();


            services.AddTransient <ITokenAdapter, TokenAdapter>();

            services.AddTransient <ICustomerServices>(serviceProvider =>
            {
                var context = serviceProvider.GetRequiredService <IHttpContextAccessor>().HttpContext;
                var header  = context.Request.Headers["protocol"];
                if (string.IsNullOrEmpty(header) || header == "http")
                {
                    return(new CustomerHttpServices
                               (serviceProvider.GetService <IConfiguration>()));
                }
                else
                {
                    return(new CustomerGrpcServices(
                               serviceProvider.GetService <ITokenAdapter>(),
                               serviceProvider.GetService <IConfiguration>()
                               ));
                }
            });
            services.AddControllers();
        }
Example #6
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jsonObject = JObject.Load(reader);
            var setting    = default(IAuthenticationConfig);

            if (jsonObject["Provider"] != null)
            {
                switch (jsonObject["Provider"].Value <string>())
                {
                case "Jwt":
                    setting = new JwtConfig(
                        jsonObject["Authority"].Value <string>(),
                        jsonObject["Audience"].Value <string>());
                    break;

                default:
                    setting = new IdentityServerConfig(
                        jsonObject["ProviderRootUrl"].Value <string>(),
                        jsonObject["ApiName"].Value <string>(),
                        jsonObject["RequireHttps"].Value <bool>(),
                        jsonObject["ApiSecret"].Value <string>());
                    break;
                }
            }
            else
            {
                setting = new IdentityServerConfig(string.Empty, string.Empty, false, string.Empty);
            }

            serializer.Populate(jsonObject.CreateReader(), setting);
            return(setting);
        }
Example #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddIdentityServer(options =>    // 注册IdentityServer4
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })                                                                          // 注册IdentityServer4
            .AddDeveloperSigningCredential()                                            // 采用开发者凭证
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())            // 添加Api资源
            .AddInMemoryClients(IdentityServerConfig.GetClients())                      // 添加客户端
            .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources()); // 添加身份资源
            // .AddResourceOwnerValidator<MyResourceOwnerValidator>();
            //.AddTestUsers(new List<IdentityServer4.Test.TestUser>() // 添加测试用户
            //{
            //     new IdentityServer4.Test.TestUser ()
            //     {
            //         Username = "******",
            //         Password = "******",
            //         SubjectId = "999"
            //     }
            //});

            // 注册服务发现服务
            //services.AddConsulServiceDiscovery();

            services.AddControllers();
        }
Example #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IWebHostEnvironment env,
            ILogger <Startup> logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            IdentityServerConfig config = Configuration
                                          .GetSection("IdentityServer").Get <IdentityServerConfig>();

            logger.LogWarning("Llego IdentityServer " + Newtonsoft.Json.JsonConvert.SerializeObject(config));


            //app.UseHttpsRedirection();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService <BancaServerGrpc>();
                endpoints.MapControllers().RequireAuthorization("Apiscope");
            });
        }
Example #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IdentityServerConfig identityConfig =
                Configuration.GetSection("IdentityServer").Get <IdentityServerConfig>();

            string cadena = Configuration.GetValue <string>("ConnectionStrings:BDCliente");

            services.AddDbContext <ClienteContext>(options => {
                options.UseSqlServer(cadena);
            });

            services.AddScoped <IClienteServices, ClienteServices>();
            services.AddScoped <ICuentaServices, CuentaServices>();

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

            services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options => {
                options.Authority                 = identityConfig.UrlServer;
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters =
                    new Microsoft.IdentityModel.Tokens.TokenValidationParameters {
                    ValidateAudience = false,
                    ValidateIssuer   = false
                };
            });

            services.AddAuthorization(opt => {
                opt.AddPolicy("Apiscope", pol => {
                    pol.RequireAuthenticatedUser();
                    pol.RequireClaim("scope", identityConfig.ResourceId);
                });
            });
        }
Example #10
0
 public UsersService(UserManager <User> userManager, IOptions <IdentityServerConfig> config,
                     IHttpClientFactory httpClientFactory)
 {
     _userManager = userManager;
     _client      = httpClientFactory.CreateClient();
     _config      = config.Value;
 }
Example #11
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // MVC
            services.AddMvc(
                options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())
                );

            IdentityRegistrar.Register(services);
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
            .AddInMemoryClients(IdentityServerConfig.GetClients())
            .AddAbpPersistedGrants <IAbpPersistedGrantDbContext>()
            .AddAbpIdentityServer <User>();;

            AuthConfigurer.Configure(services, _appConfiguration);

            services.AddScoped <IWebResourceManager, WebResourceManager>();

#if FEATURE_SIGNALR_ASPNETCORE
            services.AddSignalR();
#endif

            // Configure Abp and Dependency Injection
            return(services.AddAbp <ArkiaIdentityWebMvcModule>(
                       // Configure Log4Net logging
                       options => options.IocManager.IocContainer.AddFacility <LoggingFacility>(
                           f => f.UseAbpLog4Net().WithConfig("log4net.config")
                           )
                       ));
        }
Example #12
0
    public static void AddCustomIdentityServer(this IServiceCollection serviceCollection, IConfiguration configuration,
                                               IWebHostEnvironment environment)
    {
        var builder = serviceCollection.AddIdentityServer()
                      .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
                      .AddInMemoryApiResources(IdentityServerConfig.GetApis())
                      .AddInMemoryApiScopes(IdentityServerConfig.GetApiScopes())
                      .AddInMemoryClients(IdentityServerConfig.GetClients())
                      .AddInMemoryPersistedGrants()
                      .AddInMemoryCaching()
                      .AddProfileService <ProfileService>();

        if (environment.IsDevelopment())
        {
            builder.AddDeveloperSigningCredential();
        }
        else
        {
            builder.AddSigningCredential(new X509Certificate2(
                                             configuration.GetValue <string>("IdentityServer:Certificates:Path"),
                                             configuration.GetValue <string>("IdentityServer:Certificates:Secret")));
        }

        serviceCollection.AddTransient <IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();

        serviceCollection.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
        .AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme, x =>
        {
            x.Authority            = configuration.GetValue <string>("IdentityServer:Authority");
            x.ApiName              = configuration.GetValue <string>("IdentityServer:ApiName");
            x.RequireHttpsMetadata = configuration.GetValue <bool>("IdentityServer:RequireHttpsMetadata");
            x.RoleClaimType        = ClaimTypes.Role;
        });
    }
Example #13
0
        private void InitializeDatabase(IApplicationBuilder app)
        {
            var clientUrls = new Dictionary <string, string>
            {
                ["Mvc"]   = Configuration["ClientUrl:Mvc"],
                ["Admin"] = Configuration["ClientUrl:Admin"],
            };

            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                serviceScope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();

                var context = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();

                context.Database.Migrate();

                if (!context.Clients.Any())
                {
                    foreach (var client in IdentityServerConfig.Clients(clientUrls))
                    {
                        context.Clients.Add(client.ToEntity());
                    }

                    context.SaveChanges();
                }

                if (!context.IdentityResources.Any())
                {
                    foreach (var resource in IdentityServerConfig.Ids)
                    {
                        context.IdentityResources.Add(resource.ToEntity());
                    }

                    context.SaveChanges();
                }

                if (!context.ApiResources.Any())
                {
                    foreach (var resource in IdentityServerConfig.Apis)
                    {
                        context.ApiResources.Add(resource.ToEntity());
                    }

                    context.SaveChanges();
                }

                if (!context.ApiScopes.Any())
                {
                    foreach (var resource in IdentityServerConfig.ApiScopes)
                    {
                        context.ApiScopes.Add(resource.ToEntity());
                    }

                    context.SaveChanges();
                }
            }
        }
Example #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddDbContext <CosmosContext>(
                options =>
            {
                options.UseSqlServer(
                    Configuration.GetConnectionString("CosmosContextConnection"));
            });
            services.AddIdentity <CosmosUser, CosmosRole>()
            .AddEntityFrameworkStores <CosmosContext>()
            .AddDefaultTokenProviders();
            services.AddOptions();
            services.Configure <AppSettings>(Configuration);
            var defaultSigning = Configuration["SigningCertificate:Default"];

            if (defaultSigning == null || defaultSigning == "true")
            {
                services.AddIdentityServer(options =>
                {
                    options.PublicOrigin                  = Configuration["BaseUrls:Sts"]; //Info: For  load balancing scenarios
                    options.Events.RaiseErrorEvents       = true;
                    options.Events.RaiseInformationEvents = true;
                    options.Events.RaiseFailureEvents     = true;
                    options.Events.RaiseSuccessEvents     = true;
                })
                .AddDeveloperSigningCredential()         // Info: During Dev --> use dev cert
                .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
                .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
                .AddAspNetIdentity <CosmosUser>()
                .AddProfileService <CosmosProfileService>()
                .AddClientStore <CosmosClientStore>();
            }
            else
            {
                services.AddIdentityServer(options => options.PublicOrigin = Configuration["BaseUrls:Sts"])  // For  load balancing scenarios
                .AddSigningCredential(IdentityServerConfig.GetSigningCertificate(Configuration["SigningCertificate:Name"], Configuration["SigningCertificate:Password"]))
                .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
                .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
                .AddAspNetIdentity <CosmosUser>()
                .AddProfileService <CosmosProfileService>()
                .AddClientStore <CosmosClientStore>();
            }
            services.AddScoped <IProfileService, CosmosProfileService>();
            services.AddSingleton <IClientStore, CosmosClientStore>();

            services.AddCors();
            //Info: The below are load balancing scenarios
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders =
                    ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                options.RequireHeaderSymmetry = false;
                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });
        }
Example #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())   //配置资源
            .AddInMemoryClients(IdentityServerConfig.GetClients());            //配置客户端

            services.AddMvc();
        }
Example #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()                                     //配置id4(跟物业说我现在需要给顾客分配钥匙)
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources()) //配置允许请求的api(告诉物业我家里的哪些东西可以让顾客使用)
            .AddInMemoryClients(IdentityServerConfig.GetClients())           //配置允许哪些client请求(告诉物业满足什么条件的顾客才可以拿到我家的钥匙)
            .AddDeveloperSigningCredential();

            services.AddControllers();
        }
        public static void AddIdentityServerCustom(this IServiceCollection services,
                                                   IConfiguration configuration)
        {
            var clientUrls = new Dictionary <string, string>
            {
                ["Mvc"]   = configuration["ClientUrl:Mvc"],
                ["Admin"] = configuration["ClientUrl:Admin"],
            };

            var connectionString = configuration.GetConnectionString("ApplicationConnection");

            var assembly = typeof(Startup).Assembly.GetName().Name;

            services.AddIdentity <IdentityUser, IdentityRole>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(config =>
            {
                // config.Cookie.Name = "server";
                config.LoginPath  = "/Auth/Login";
                config.LogoutPath = "/Auth/Logout";
            });

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
            .AddAspNetIdentity <IdentityUser>()
            // .AddConfigurationStore(options =>
            // {
            //     options.ConfigureDbContext = b => b.UseSqlServer(connectionString,
            //         sql => sql.MigrationsAssembly(assembly));
            // })
            // .AddOperationalStore(options =>
            // {
            //     options.ConfigureDbContext = b =>
            //         b.UseSqlServer(connectionString, sql =>
            //             sql.MigrationsAssembly(assembly));
            // })
            .AddProfileService <ProfileService>()
            .AddInMemoryIdentityResources(IdentityServerConfig.Ids)
            .AddInMemoryApiResources(IdentityServerConfig.Apis)
            .AddInMemoryClients(IdentityServerConfig.Clients(clientUrls))
            .AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
            .AddDeveloperSigningCredential();
            // .AddTestUsers(TestUsers.Users)
        }
Example #18
0
 public UserService(
     IUserStore <T> userStore,
     IPasswordHasher <T> passwordHasher,
     IOptions <IdentityServerConfig> options)
 {
     _userStore      = userStore;
     _passwordHasher = passwordHasher;
     _options        = options.Value;
 }
Example #19
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddCors();
     services.AddIdentityServer()
     .AddDeveloperSigningCredential()
     .AddInMemoryClients(IdentityServerConfig.GetClients())
     .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
     .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
     .AddTestUsers(IdentityServerConfig.GetUsers());
 }
Example #20
0
        public static IApplicationBuilder UseIdentityServerConfigs(this IApplicationBuilder app)
        {
            using var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope();
            var context = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();

            IdentityServerConfig.SaveIdentityResources(context);
            IdentityServerConfig.SaveApis(context);
            IdentityServerConfig.SaveClients(context);
            return(app);
        }
Example #21
0
        public void Configuration(IAppBuilder app)
        {
            //var fileName = $@"{AppDomain.CurrentDomain.BaseDirectory}Logging\\Log.txt";

            //Log.Logger = new LoggerConfiguration()
            //    .WriteTo.RollingFile(fileName)
            //    .CreateLogger();

            IdentityServerConfig.ConfigureIdentityServer(app);
        }
Example #22
0
 public IEnumerable <User> GetUsers()
 {
     return
         (IdentityServerConfig.GetUsers().Select(o => new User
     {
         Email = o.Claims.Single(claim => claim.Type == "email").Value,
         Id = o.Subject,
         UserName = o.Username
     }));
 }
Example #23
0
 // This method gets called by the runtime. Use this method to add services to the container.
 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddIdentityServer()
     .AddDeveloperSigningCredential()
     .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResourceResources())
     .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
     .AddInMemoryClients(IdentityServerConfig.GetClients())
     .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>()
     .AddProfileService <ProfileService>();
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            // configure identity server with in-memory stores, keys, clients and scopes
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
            .AddInMemoryClients(IdentityServerConfig.GetClients())
            .AddTestUsers(IdentityServerConfig.GetUsers());
        }
Example #25
0
        public static IHost MigrateDatabase(this IHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                scope.ServiceProvider
                .GetRequiredService <PersistedGrantDbContext>()
                .Database
                .Migrate();

                using (var context = scope.ServiceProvider
                                     .GetRequiredService <ConfigurationDbContext>())
                {
                    try
                    {
                        context.Database.Migrate();

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

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

                        if (!context.ApiResources.Any())
                        {
                            foreach (var apiScope in IdentityServerConfig.GetApiResources())
                            {
                                context.ApiResources.Add(apiScope.ToEntity());
                            }
                            context.SaveChanges();
                        }
                    }
                    catch (Exception ex)
                    {
                        //Log errors or do anything you think it's needed
                        throw;
                    }
                }
            }

            return(host);
        }
        public static void AddIdentityServerConfig(this IServiceCollection services, AuthSettings authSettings)
        {
            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents = true;
                // options.Events.RaiseFailureEvents = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseSuccessEvents     = true;
                options.UserInteraction.LoginUrl      = $"{authSettings.Authority}/auth/login";
                options.UserInteraction.LogoutUrl     = $"{authSettings.Authority}/auth/logout";
                options.IssuerUri = authSettings.Authority;
            })
            .AddDeveloperSigningCredential()
            .AddJwtBearerClientAuthentication()
            .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
            .AddInMemoryApiScopes(IdentityServerConfig.GetScopes())
            .AddInMemoryClients(authSettings.Clients)
            .AddAspNetIdentity <User>();

            services.AddAuthentication()
            .AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme,
                                             options =>
            {
                options.Authority            = authSettings.Authority;
                options.SaveToken            = true;
                options.RequireHttpsMetadata = false;

                if (!authSettings.MetadataAddress.IsEmpty())
                {
                    options.MetadataAddress = authSettings.MetadataAddress;
                }

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience         = false,
                    ValidateIssuerSigningKey = false,
                    ValidateIssuer           = false,
                    NameClaimType            = "name",
                    RoleClaimType            = "role"
                };
            },
                                             null)
            .AddGoogle(options =>
            {
                options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                options.ClientId     = authSettings.GoogleSettings.ClientId;
                options.ClientSecret = authSettings.GoogleSettings.ClientSecret;
            });

            services.AddAuthorization();
        }
Example #27
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     // configure identity server with in-memory stores, keys, clients and scopes
     services.AddIdentityServer()
     .AddDeveloperSigningCredential()
     .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources()) // 身份资源
     .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())           // api资源
     .AddInMemoryClients(IdentityServerConfig.GetClients())                     // Client资源
     //.AddTestUsers(IdentityServerConfig.GetUsers())            // 测试用户数据
     .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>()              // 校验器
     .AddProfileService <ProfileService>();                                     //
 }
Example #28
0
 public void ConfigureServices(IServiceCollection services)
 {
     if (NancyWebAppConfig.IdentityServerEnabled)
     {
         services
         .AddIdentityServer()
         .AddTemporarySigningCredential()
         .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
         .AddInMemoryClients(IdentityServerConfig.GetClients())
         .AddInMemoryUsers(IdentityServerConfig.GetUsers());
     }
 }
Example #29
0
        public static void RegisterAccountDependencies(this IServiceCollection services, IConfiguration configuration, bool isProduction)
        {
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <IdentityContext>()
            .AddDefaultTokenProviders();

            var builder = services.AddIdentityServer(options => {
                options.IssuerUri = "null";
                options.UserInteraction.LoginUrl      = "/Accounts/SignIn";
                options.UserInteraction.LogoutUrl     = "/Accounts/SignOut";
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
                          .AddInMemoryIdentityResources(IdentityServerConfig.Ids)
                          .AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
                          .AddInMemoryApiResources(IdentityServerConfig.Apis)
                          .AddInMemoryClients(IdentityServerConfig.GetClients(configuration))
                          .AddAspNetIdentity <ApplicationUser>();

            builder.Services.AddScoped <IProfileService, ProfileService>();

            if (isProduction)
            {
                var client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(async(authority, resource, scope) =>
                {
                    var context              = new AuthenticationContext(authority);
                    var credentials          = new ClientCredential(configuration.GetValue <string>("AzureKeyVaultClientId"), configuration.GetValue <string>("AzureKeyVaultClientSecret"));
                    var authenticationResult = await context.AcquireTokenAsync(resource, credentials);
                    return(authenticationResult.AccessToken);
                }));

                builder.AddSigningCredential(new X509Certificate2(Convert.FromBase64String(client.GetSecretAsync(configuration.GetValue <string>("AzureKeyVaultGiuruIdentityServer4Certificate")).Result.Value), configuration.GetValue <string>("AzureKeyVaultGiuruIdentityServer4CertificatePassword")));
            }
            else
            {
                builder.AddDeveloperSigningCredential();
            }

            services.AddAuthentication()
            .AddIdentityServerAuthentication("IsToken", options =>
            {
                options.Authority            = configuration.GetValue <string>("IdentityUrl");
                options.RequireHttpsMetadata = false;
                options.ApiName = AccountConstants.ApiNames.All;
            });

            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IAppSecretRepository, AppSecretRepository>();
        }
Example #30
0
        public static IServiceCollection ConfigureIdentityServer(this IServiceCollection services)
        {
            var hostingEnviroment = services.BuildServiceProvider().GetService <IHostingEnvironment>();

            services
            .AddIdentityServer()
            .AddSigningCredential(new X509Certificate2(Path.Combine(hostingEnviroment.ContentRootPath, "Certs", "certificadocore.pfx")))
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
            .AddInMemoryClients(IdentityServerConfig.GetClients())
            .AddAspNetIdentity <Usuario>()
            .AddCustomUserStore();

            return(services);
        }