public static void UseSimpleIdentityServerManager(
            this IApplicationBuilder applicationBuilder,
            ILoggerFactory loggerFactory,
            ManagerOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (options.Introspection == null)
            {
                throw new ArgumentNullException(nameof(options.Introspection));
            }

            // 1. Use log.
            loggerFactory.AddSerilog();
            // 2. Display status code page.
            applicationBuilder.UseStatusCodePages();
            // 3. Enable CORS
            applicationBuilder.UseCors("AllowAll");
            // 4. Enable custom exception handler
            applicationBuilder.UseSimpleIdentityServerManagerExceptionHandler(new ExceptionHandlerMiddlewareOptions
            {
                ManagerEventSource = (IManagerEventSource)applicationBuilder.ApplicationServices.GetService(typeof(IManagerEventSource))
            });
            // 5. Enable introspection.
            var introspectionOptions = new Oauth2IntrospectionOptions
            {
                InstrospectionEndPoint = options.Introspection.IntrospectionUrl,
                ClientId     = options.Introspection.ClientId,
                ClientSecret = options.Introspection.ClientSecret
            };

            applicationBuilder.UseAuthenticationWithIntrospection(introspectionOptions);
            // 6. Launch ASP.NET API
            applicationBuilder.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}");
            });
        }
Beispiel #2
0
        public static void AddSimpleIdentityServerManager(this IServiceCollection serviceCollection, ManagerOptions managerOptions)
        {
            if (managerOptions == null)
            {
                throw new ArgumentNullException(nameof(managerOptions));
            }

            // 1. Add the dependencies needed to enable CORS
            serviceCollection.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                                   .AllowAnyMethod()
                                                                   .AllowAnyHeader()));
            // 2. Register all the dependencies.
            serviceCollection.AddSimpleIdentityServerCore();
            serviceCollection.AddSimpleIdentityServerManagerCore();
            // 3. Add authorization policies
            serviceCollection.AddAuthorization(options =>
            {
                options.AddPolicy("manager", policy =>
                {
                    policy.AddAuthenticationSchemes("UserInfoIntrospection", "OAuth2Introspection");
                    policy.RequireAssertion(p =>
                    {
                        if (p.User == null || p.User.Identity == null || !p.User.Identity.IsAuthenticated)
                        {
                            return(false);
                        }

                        var claimRole  = p.User.Claims.FirstOrDefault(c => c.Type == "role");
                        var claimScope = p.User.Claims.FirstOrDefault(c => c.Type == "scope");
                        if (claimRole == null && claimScope == null)
                        {
                            return(false);
                        }

                        return(claimRole != null && claimRole.Value == "administrator" || claimScope != null && claimScope.Value == "manager");
                    });
                });
            });
            // 5. Add JWT parsers.
            serviceCollection.AddSimpleIdentityServerJwt();
            // 6. Add the dependencies needed to run MVC
            serviceCollection.AddTechnicalLogging();
            serviceCollection.AddManagerLogging();
            serviceCollection.AddOAuthLogging();
            serviceCollection.AddOpenidLogging();
            // TH : REMOVE THIS SERVICE LATER...
            serviceCollection.AddTransient <IPasswordService, DefaultPasswordService>();
        }
        public static void AddSimpleIdentityServerManager(
            this IServiceCollection serviceCollection,
            ManagerOptions managerOptions)
        {
            if (managerOptions == null)
            {
                throw new ArgumentNullException(nameof(managerOptions));
            }

            if (managerOptions.Logging == null)
            {
                throw new ArgumentNullException(nameof(managerOptions.Logging));
            }

            if (managerOptions.PasswordService == null)
            {
                serviceCollection.AddTransient <IPasswordService, DefaultPasswordService>();
            }
            else
            {
                serviceCollection.AddSingleton(managerOptions.PasswordService);
            }

            if (managerOptions.AuthenticateResourceOwnerService == null)
            {
                serviceCollection.AddTransient <IAuthenticateResourceOwnerService, DefaultAuthenticateResourceOwerService>();
            }
            else
            {
                serviceCollection.AddSingleton(managerOptions.AuthenticateResourceOwnerService);
            }

            // 1. Add the dependencies needed to enable CORS
            serviceCollection.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                                   .AllowAnyMethod()
                                                                   .AllowAnyHeader()));
            // 2. Register all the dependencies.
            serviceCollection.AddSimpleIdentityServerCore();
            serviceCollection.AddSimpleIdentityServerManagerCore();
            serviceCollection.AddConfigurationClient();
            serviceCollection.AddIdServerClient();
            // 3. Register the dependencies to run the authentication.
            serviceCollection.AddAuthentication();
            // 4. Add authorization policies
            serviceCollection.AddAuthorization(options =>
            {
                options.AddPolicy("manager", policy => policy.RequireClaim("scope", "openid_manager"));
            });
            // 5. Add JWT parsers.
            serviceCollection.AddSimpleIdentityServerJwt();
            // 6. Add the dependencies needed to run MVC
            serviceCollection.AddMvc();
            // 7. Configure Serilog
            Func <LogEvent, bool> serilogFilter = (e) =>
            {
                var ctx          = e.Properties["SourceContext"];
                var contextValue = ctx.ToString()
                                   .TrimStart('"')
                                   .TrimEnd('"');
                return(contextValue.StartsWith("SimpleIdentityServer") ||
                       e.Level == LogEventLevel.Error ||
                       e.Level == LogEventLevel.Fatal);
            };
            var logger = new LoggerConfiguration()
                         .MinimumLevel.Information()
                         .Enrich.FromLogContext()
                         .WriteTo.ColoredConsole();

            if (managerOptions.Logging.FileLogOptions != null &&
                managerOptions.Logging.FileLogOptions.IsEnabled)
            {
                logger.WriteTo.RollingFile(managerOptions.Logging.FileLogOptions.PathFormat);
            }
            if (managerOptions.Logging.ElasticsearchOptions != null &&
                managerOptions.Logging.ElasticsearchOptions.IsEnabled)
            {
                logger.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(managerOptions.Logging.ElasticsearchOptions.Url))
                {
                    AutoRegisterTemplate = true,
                    IndexFormat          = "manager-{0:yyyy.MM.dd}",
                    TemplateName         = "manager-events-template"
                });
            }

            var log = logger.Filter.ByIncludingOnly(serilogFilter)
                      .CreateLogger();

            Log.Logger = log;
            serviceCollection.AddLogging();
            serviceCollection.AddTransient <IManagerEventSource, ManagerEventSource>();
            serviceCollection.AddTransient <ISimpleIdentityServerEventSource, SimpleIdentityServerEventSource>();
        }