Beispiel #1
0
 public void ConfigureServices(IServiceCollection services)
 {
     services
     .AddIdentityServer()
     .AddDeveloperSigningCredential()
     .AddInMemoryApiResources(IdentityConfig.GetApiResources())
     .AddInMemoryClients(IdentityConfig.GetClients())
     .AddTestUsers(IdentityConfig.GetUsers());
 }
        // 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()
            .AddTemporarySigningCredential()
            .AddTestUsers(IdentityConfig.GetTestUsers())
            .AddInMemoryApiResources(IdentityConfig.GetApiResources())
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryClients(IdentityConfig.GetClients());

            services.AddMvc();
        }
Beispiel #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IConfiguration>(Configuration);

            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.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddAzureAd(Configuration.GetSection("IdentityProvider:AzureAd").Get <AzureAdConfig>())
            .AddAzureAdB2C(Configuration.GetSection("IdentityProvider:AzureAdB2C").Get <AzureAdB2CConfig>())
            .AddCookie(options =>
            {
                options.Events.OnRedirectToLogin = context =>
                {
                    context.Response.Headers["Location"] = context.RedirectUri;
                    context.Response.StatusCode          = 401;
                    return(Task.CompletedTask);
                };
            });

            // Identity Server
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityConfig.GetApiResources(Configuration))
            .AddInMemoryClients(IdentityConfig.GetClients(Configuration))
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();

            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout     = TimeSpan.FromHours(1);
                options.Cookie.HttpOnly = true;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddSessionStateTempDataProvider();;
        }
Beispiel #4
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMultiTenancy <TenantResolutionFromTokenValidationLibrary>();

            services.AddEarlyLogging(out var earlyLogger);
            earlyLogger.LogInformation("starting to configure services...");

            services.AddCors(options => options.AddPolicy("mycustomcorspolicy", b => b.WithOrigins("http://meinetollewebsite.de").AllowAnyMethod().AllowAnyHeader()));
            services.AddMvc();

            services.AddSingleton <IConfigureOptions <CookieAuthenticationOptions>, ConfigureCookieOptions>();
            services.AddIdentityServer()
            .AddSigningCredentialFromKeyVault(config, earlyLogger)
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityConfig.GetApis())
            .AddInMemoryApiScopes(IdentityConfig.GetScopes())
            .AddInMemoryClients(IdentityConfig.GetClients())
            .AddTestUsers(IdentityConfig.GetTestUsers())
            ;

            services.AddScoped <DisposeTest>();
            services.AddAuthentication();
            services.AddAuthorization(o =>
            {
                o.AddPolicy("default", b =>
                {
                    b.RequireAuthenticatedUser();
                    b.RequireClaim(JwtClaimTypes.Subject);//windows authenticated but no authenticated cookie (logged out) shouldbe treated as unauthenticated.
                });
            });

            services.AddTransient <RequestFromOnPremise>();

            services.AddTransientDecorator <ICorsPolicyProvider, CorsPolicyProvider>();
            services.AddTransientDecorator <IAuthorizeRequestValidator, ExtendedAuthorizeRequestValidator>();

            services.AddSingleton <IResolvedTenant>(new ResolvedTenant("default"));

            earlyLogger.LogInformation("done configuring general services :)");
        }
Beispiel #5
0
        /// <summary>
        /// Configures the services.
        /// </summary>
        /// <param name="services">The services.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <IdentityDbContext>(o =>
            {
                o.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                               sqlOptions => sqlOptions.EnableRetryOnFailure(50, TimeSpan.FromSeconds(30), null));
            });

            services.AddScoped <DbContext, IdentityDbContext>();
            services.AddScoped <IIdentityUserService, IdentityUserService>();
            services.AddScoped <IIdentityUserRepository, IdentityUserRepository>();

            // configures the OpenIdConnect handlers to persist the state parameter into the server-side IDistributedCache.
            services.AddOidcStateDataFormatterCache();

            services.AddControllersWithViews();

            IIdentityServerBuilder builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents =
                    true;
                options.Events.RaiseFailureEvents = true;
                options.Events.RaiseSuccessEvents = true;
                options.PublicOrigin = Config.Self.PublicOrigin;
                if (Environment.IsDevelopment())
                {
                    options.IssuerUri = Config.Self.IssuerUri;
                }
            });

            builder.AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources());
            builder.AddInMemoryApiResources(IdentityConfig.Apis);
            builder.AddInMemoryClients(IdentityConfig.Clients(Config));
            builder.Services.AddTransient <IProfileService, ProfileService>();
            services.AddSingleton(Config);

            // sets the authentication schema.
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = IdentityServerConstants.DefaultCookieAuthenticationScheme;
                options.DefaultSignInScheme       = IdentityServerConstants.DefaultCookieAuthenticationScheme;
                options.DefaultChallengeScheme    = IdentityServerConstants.DefaultCookieAuthenticationScheme;
            })
            // Adds Fontys Single Sign On authentication.
            .AddOpenIdConnect("FHICT", "Fontys", options =>
            {
                options.ClientId     = Config.FfhictOIDC.ClientId;
                options.ClientSecret = Config.FfhictOIDC.ClientSecret;
                options.Authority    = Config.FfhictOIDC.Authority;
                options.ResponseType = "code";
                options.Scope.Clear();

                string[] scopes = Config.FfhictOIDC.Scopes.Split(" ");
                foreach (string scope in scopes)
                {
                    options.Scope.Add(scope);
                }

                // Set this flow to get the refresh token.
                // options.Scope.Add("offline_access");

                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;

                // This sets the redirect uri, this is needed because the blackbox implementation does not implement fontys SSO.
                options.Events.OnRedirectToIdentityProvider = async n =>
                {
                    n.ProtocolMessage.RedirectUri = Config.FfhictOIDC.RedirectUri;
                    await Task.FromResult(0);
                };
            }
                              // Add jwt validation this is so that the DGS can authenticate.
                              ).AddJwtBearer(o =>
            {
                o.SaveToken                 = true;
                o.Authority                 = Config.Self.JwtAuthority;
                o.RequireHttpsMetadata      = false;
                o.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateActor    = false,
                    ValidateAudience = false,
                    NameClaimType    = "name",
                    RoleClaimType    = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
                };
            })
            .AddCookie();

            if (Environment.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                certStore.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certCollection = certStore.Certificates.Find(
                    X509FindType.FindByIssuerName,
                    "Let's Encrypt Authority X3",
                    false
                    );
                if (certCollection.Count > 0)
                {
                    X509Certificate2 certificate = certCollection[0];
                    builder.AddSigningCredential(certificate);
                }
            }

            // TODO tighten cors
            services.AddCors(options =>
            {
                options.AddPolicy("dex-api",
                                  policy =>
                {
                    policy.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });
        }
 public IdentityServerParameters(IOptions <IdentityConfig> configuration)
 {
     this.Configuration = configuration.Value;
 }