Exemple #1
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddIdentityServer()
     .AddSigningCredential(IdentityServerBuilderExtensionsCrypto.CreateRsaSecurityKey())
     .AddInMemoryApiResources(Config.GetApis())
     .AddInMemoryClients(Config.GetClients());
 }
Exemple #2
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(x => x.AddPolicy("AllowAnyOrigin", y => {
                y.AllowAnyOrigin();
                y.AllowAnyMethod();
                y.AllowAnyHeader();
            }));

            var builder = services.AddIdentityServer()
                          .AddTestUsers(Config.GetUsers())
                          //.AddInMemoryIdentityResources(Config.GetIdentityResources())
                          //.AddClientStore<IClientStore>()
                          .AddInMemoryApiResources(Config.GetApis())
                          .AddInMemoryClients(Config.GetClients());

            if (Environment.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                var key = IdentityServerBuilderExtensionsCrypto.CreateRsaSecurityKey();
                builder.AddSigningCredential(key);
            }
        }
Exemple #3
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddIdentityServer()
            .AddInMemoryApiResources(Config.GetApis())
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryClients(Config.GetClients())
            .AddTestUsers(TestUsers.Users)
            .AddSigningCredential(IdentityServerBuilderExtensionsCrypto.CreateRsaSecurityKey());

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

                options.ClientId     = "708996912208-9m4dkjb5hscn7cjrn5u0r4tbgkbj1fko.apps.googleusercontent.com";
                options.ClientSecret = "wdfPY6t8H8cecgjlxud__4Gh";
            })
            .AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Authority = "https://demo.identityserver.io";

                options.ApiName   = "api";
                options.ApiSecret = "secret";
            });

            // demo versions
            services.AddTransient <IRedirectUriValidator, DemoRedirectValidator>();
            services.AddTransient <ICorsPolicyService, DemoCorsPolicy>();
        }
Exemple #4
0
        private static SecurityKey GetSecurityKey()
        {
            var key = "Test";

            var param = new RSAParameters
            {
                D = Encoding.ASCII.GetBytes(key),
            };


            return(IdentityServerBuilderExtensionsCrypto.CreateRsaSecurityKey(param, "2a2467e4a208110eb83896572a7c10af"));
        }
Exemple #5
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddSigningCredential(IdentityServerBuilderExtensionsCrypto.CreateRsaSecurityKey())
            .AddInMemoryIdentityResources(Config.GetIdentityResourceResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>()
            .AddProfileService <ProfileService>()
            ;

            services.AddDbContext <IDSContext>(options => {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });
        }
Exemple #6
0
        protected override void ConfigureServicesInternal(IServiceCollection services)
        {
            services.AddSerilog(Configuration);
            services.AddSingleton <ICacheStrategy <MethodCacheObject>, DefaultCacheStrategy <MethodCacheObject> >();

            var database = MongoUrl.Create(ServiceConfiguration.MongoConnectionString).DatabaseName;

            var mongoDbContext = new MongoDbContext(ServiceConfiguration.MongoConnectionString, database);

            services.AddIdentity <ApplicationUser, ApplicationRole>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 1;
                options.Password.RequiredUniqueChars    = 1;
            })
            .AddMongoDbStores <IMongoDbContext>(mongoDbContext)
            .AddDefaultTokenProviders();

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseSuccessEvents     = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
            })
            .AddMongoStores()
            .AddProfileService <AllAvailableClaimsProfileService>()
            .AddSigningCredential(IdentityServerBuilderExtensionsCrypto.CreateRsaSecurityKey())
            .Services.AddTransient <IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();

            services.AddAuthorization(options =>
            {
                options.AddPolicy(AzurePlaygroundConstants.Auth.AdminRolePolicy, policy => policy.RequireRole(AzurePlaygroundConstants.Auth.AdminRoleClaimValue));
            });

            services.AddSwagger(ServiceConfiguration);

            var jsonSettings = new TradeServiceJsonSerializerSettings();

            services.AddMvc()
            .RegisterJsonSettings(jsonSettings)
            .AddFluentValidation(config => config.RegisterValidatorsFromAssemblies((assembly) => assembly.FullName.Contains("AzurePlayground")));
        }
Exemple #7
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);

            var builder = services.AddIdentityServer()
                          .AddInMemoryIdentityResources(Config.GetIdentityResources())
                          .AddInMemoryApiResources(Config.GetApis())
                          .AddInMemoryClients(Config.GetClients())
                          .AddTestUsers(Config.GetUsers());

            if (Environment.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                // TODO: this does not work in a scale-out env like Azure Functions!!!
                builder.AddSigningCredential(IdentityServerBuilderExtensionsCrypto.CreateRsaSecurityKey());
            }
        }
Exemple #8
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_2);

            services.AddDbContext <BringItAuthDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("Default"), x => x.MigrationsAssembly("BringIt.Auth.Api")));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <BringItAuthDbContext>()
            .AddDefaultTokenProviders();
            var ss       = IdentityServerBuilderExtensionsCrypto.CreateRsaSecurityKey();
            var builder1 = services.AddIdentityServer(options =>
            {
                options.IssuerUri = null;
            }).AddSigningCredential(ss)
                           .AddInMemoryIdentityResources(Config.GetIdentityResources())
                           .AddInMemoryClients(Config.GetClients())
                           .AddInMemoryApiResources(Config.GetApis())
                           .AddAspNetIdentity <ApplicationUser>();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "AuthKey";
            }).AddJwtBearer("AuthKey", options =>
            {
                options.Authority            = "http://bringit.auth.api:80";
                options.RequireHttpsMetadata = false;
                options.Audience             = "api1";
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Account API", Version = "v1"
                });
            });
        }
Exemple #9
0
        public JwtRequestAuthorizeTests()
        {
            IdentityModelEventSource.ShowPII = true;

            _rsaKey = IdentityServerBuilderExtensionsCrypto.CreateRsaSecurityKey();

            _mockPipeline.Clients.AddRange(new Client[] {
                _client = new Client
                {
                    ClientName = "Client with keys",
                    ClientId   = "client",
                    Enabled    = true,

                    RedirectUris = { "https://client/callback" },

                    ClientSecrets =
                    {
                        new Secret
                        {
                            Type  = IdentityServerConstants.SecretTypes.X509CertificateBase64,
                            Value = Convert.ToBase64String(TestCert.Load().Export(X509ContentType.Cert))
                        },
                        new Secret
                        {
                            Type  = IdentityServerConstants.SecretTypes.JsonWebKey,
                            Value = _symmetricJwk
                        },
                        new Secret
                        {
                            Type  = IdentityServerConstants.SecretTypes.JsonWebKey,
                            Value = JsonConvert.SerializeObject(JsonWebKeyConverter.ConvertFromRSASecurityKey(_rsaKey))
                        },
                        // turning a x509 JWK into an X509 security key does not seem to work... (KeySize = 0)
                        //new Secret
                        //{
                        //    Type = IdentityServerConstants.SecretTypes.JsonWebKey,
                        //    Value = JsonConvert.SerializeObject(JsonWebKeyConverter.ConvertFromX509SecurityKey(new X509SecurityKey(TestCert.Load())))
                        //}
                    },

                    AllowedGrantTypes = GrantTypes.Implicit,

                    AllowedScopes = new List <string>
                    {
                        "openid", "profile", "api1", "api2"
                    }
                },
            });

            _mockPipeline.Users.Add(new TestUser
            {
                SubjectId = "bob",
                Username  = "******",
                Claims    = new Claim[]
                {
                    new Claim("name", "Bob Loblaw"),
                    new Claim("email", "*****@*****.**"),
                    new Claim("role", "Attorney")
                }
            });

            _mockPipeline.IdentityScopes.AddRange(new IdentityResource[] {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
                new IdentityResources.Email()
            });
            _mockPipeline.ApiScopes.AddRange(new ApiResource[] {
                new ApiResource
                {
                    Name   = "api",
                    Scopes =
                    {
                        new Scope
                        {
                            Name = "api1"
                        },
                        new Scope
                        {
                            Name = "api2"
                        }
                    }
                }
            });

            _mockPipeline.Initialize();
        }
Exemple #10
0
        public void ConfigureAuthServices(IServiceCollection services, ServerSettings serverSettings)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary <string, string>();
            string connectionString   = this.Configuration.GetConnectionString("DefaultConnection");
            var    migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext <UnityAuthDbContext>(options =>
            {
                options.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
            });

            services.AddIdentity <ApplicationUser, ApplicationUserRole>()
            .AddRoleManager <ApplicationUserRoleManager>()
            .AddUserManager <ApplicationUserManager>()
            .AddEntityFrameworkStores <UnityAuthDbContext>()
            .AddDefaultTokenProviders();

            // configure identity server with in-memory stores, keys, clients and scopes
            services.AddIdentityServer()

            // .AddClientStore<UnityClientStore>()
            .AddProfileService <UnityUserProfileService>()

            // .AddClientStoreCache<UnityClientStore>()
            .AddSigningCredential(IdentityServerBuilderExtensionsCrypto.CreateRsaSecurityKey())

            // this adds the config data from DB (clients, resources)
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(
                    connectionString,
                    sql => sql.MigrationsAssembly(migrationsAssembly));
            })

            // this adds the operational data from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(
                    connectionString,
                    sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup   = true;
                options.TokenCleanupInterval = SessionSecurity.TokenCleanupInterval;
            })
            .AddDefaultEndpoints()
            .AddRequiredPlatformServices()

            // .AddInMemoryPersistedGrants()
            // .AddInMemoryIdentityResources(Defaults.GetIdentityResources())
            // .AddInMemoryApiResources(Defaults.GetApiResources())
            // .AddInMemoryClients(Defaults.GetClients())
            .AddAspNetIdentity <ApplicationUser>();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = serverSettings.HostAddress;
                options.ApiName              = "api";
                options.RequireHttpsMetadata = false;
                options.SaveToken            = true;
                options.ApiSecret            = "secret";
                options.SupportedTokens      = SupportedTokens.Both;
                options.JwtBearerEvents      = new AuthJwtBearerEvents();
            });

            services.Configure <IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequireDigit           = true;
                options.Password.RequiredLength         = 6;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = true;
                options.Password.RequireLowercase       = false;
                options.Password.RequiredUniqueChars    = 6;

                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(30);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                // User settings
                options.User.RequireUniqueEmail = true;
            });

            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly   = true;
                options.Cookie.Expiration = TimeSpan.FromMinutes(SessionSecurity.SessionExpiryTime);
                options.LoginPath         = "/Account/Login";        // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
                options.LogoutPath        = "/Account/Logout";       // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
                options.AccessDeniedPath  = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
                options.SlidingExpiration = true;
            });

            // services
            //    .AddMvcCore(options =>
            //    {
            //        // require scope1 or scope2
            //        var policy = ScopePolicy.Create("apiv1");
            //        options.Filters.Add(new AuthorizeFilter(policy));
            //    })
            //    .AddJsonFormatters()
            //    .AddAuthorization();

            // services.AddAuthorization(options =>
            // {
            //    options.AddPolicy("apiv1Policy", builder =>
            //    {
            //        // require scope1
            //        builder.RequireScope("apiv1");
            //    });
            // });

            // add CORS policy for non-IdentityServer endpoints
            services.AddCors(options =>
            {
                options.AddPolicy("apiCorsPolicy", policy =>
                {
                    policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
                });
            });

            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();

            // Add application services.
            services.AddTransient <ISmsSender, SmsSender>();
            services.AddSingleton <TokenCleanup>();
            services.AddSingleton <IHostedService, TokenCleanupHost>();

            var storeOptions = new OperationalServiceOptions();

            services.AddSingleton(storeOptions);

            storeOptions.EnableTokenCleanup    = true;
            storeOptions.TokenCleanupInterval  = Convert.ToInt32(TimeSpan.FromMinutes(SessionSecurity.SessionExpiryTime).TotalSeconds);
            storeOptions.TokenCleanupBatchSize = SessionSecurity.TokenCleanupBatchSize;
        }