コード例 #1
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)
        {
            var oAuth2EndpointInfo = new IdentityServer4Info("https://*****:*****@"TFGB=?Gf3UvH+Uqfu_5p", "Orleans");

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.SupportedTokens = SupportedTokens.Both;
                options.Authority       = oAuth2EndpointInfo.Url;
                options.ApiName         = oAuth2EndpointInfo.ClientId;
                options.ApiSecret       = oAuth2EndpointInfo.ClientSecret;
                options.SaveToken       = true;
            });

            services.AddControllers();
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // ReSharper disable once RedundantTypeArgumentsOfMethod
            services.AddSingleton <IClusterClient>(serviceProvider =>
            {
                OrleansClusterClientProvider.StartClientWithRetries(out var client,
                                                                    serviceProvider.GetService <IHttpContextAccessor>(), oAuth2EndpointInfo);

                return(client);
            });
        }
コード例 #2
0
        private static IClusterClient Build(IHttpContextAccessor contextAccessor,
                                            IdentityServer4Info identityServer4Info)
        {
            var builder = new ClientBuilder()
                          .UseLocalhostClustering()
                          .Configure <ClusterOptions>(options =>
            {
                options.ClusterId = "Orleans.Security.Test";
                options.ServiceId = "ServiceId1";
            })
                          .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(IUserGrain).Assembly).WithReferences())
                          .ConfigureLogging(logging => logging.AddConsole())
                          .ConfigureServices(services =>
            {
                services.AddOrleansClusteringAuthorization(identityServer4Info,
                                                           config =>
                {
                    config.ConfigureAuthorizationOptions       = AuthorizationConfig.ConfigureOptions;
                    config.ConfigureAccessTokenVerifierOptions = options =>
                    {
                        options.InMemoryCacheEnabled = true;
                    };

                    config.TracingEnabled = true;
                });

                services.AddSingleton <Func <IHttpContextAccessor> >(serviceProvider => () => contextAccessor);
                services.AddScoped <IAccessTokenProvider, AspNetCoreAccessTokenProvider>();
            });

            return(builder.Build());
        }
        public OutgoingGrainCallAuthorizationFilter(IAccessTokenProvider accessTokenProvider,
                                                    IAccessTokenVerifier accessTokenVerifier,
                                                    IdentityServer4Info identityServer4Info, IAuthorizationExecutor authorizeHandler,
                                                    ILoggerFactory loggerFactory) : base(accessTokenVerifier, authorizeHandler)
        {
            _accessTokenProvider = accessTokenProvider;
            _identityServer4Info = identityServer4Info;

            Logger = loggerFactory.CreateLogger <OutgoingGrainCallAuthorizationFilter>();
        }
 public AccessTokenIntrospectionServiceDefault(IHttpClientFactory clientFactory,
     IdentityServer4Info identityServer4Info,
     IdS4DiscoveryDocumentProvider discoveryDocumentProvider,
     ILogger<AccessTokenIntrospectionServiceDefault> logger)
 {
     _httpClient = clientFactory.CreateClient("IdS4");
     _identityServer4Info = identityServer4Info;
     _discoveryDocumentProvider = discoveryDocumentProvider;
     _logger = logger;
 }
 public OrleansClusterClientProvider(
     IHttpContextAccessor httpContextAccessor, ILogger logger,
     IdentityServer4Info identityServer4Info,
     string simpleClusterAzureStorageConnection, TelemetryClient telemetryClient)
 {
     _httpContextAccessor = httpContextAccessor;
     _logger = logger;
     _identityServer4Info = identityServer4Info;
     _simpleClusterAzureStorageConnection = simpleClusterAzureStorageConnection;
     _telemetryClient = telemetryClient;
 }
コード例 #6
0
ファイル: Program.cs プロジェクト: Async-Hub/Orleans.Security
        public static void Main(string[] args)
        {
            _identityServer4Info = new IdentityServer4Info("http://*****:*****@"TFGB=?Gf3UvH+Uqfu_5p", "Orleans");

            // TODO: Audience validation logic
            // https://leastprivilege.com/2020/06/15/the-jwt-profile-for-oauth-2-0-access-tokens-and-identityserver/
            //_identityServer4Info = new IdentityServer4Info("https://*****:*****@3x3g*RLez$TNU!_7!QW", "Orleans");

            CreateHostBuilder(args).Build().Run();
        }
コード例 #7
0
ファイル: Startup.cs プロジェクト: Async-Hub/Orleans.Security
        // 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)
        {
            var oAuth2EndpointInfo = new IdentityServer4Info("http://*****:*****@"TFGB=?Gf3UvH+Uqfu_5p", "Orleans");

            services.AddAuthentication("token")
            // JWT tokens
            .AddJwtBearer("token", options =>
            {
                // For development environments only. Do not use for production.
                options.RequireHttpsMetadata = false;

                options.Authority = oAuth2EndpointInfo.Url;
                options.Audience  = "Api1";
                options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
                options.TokenValidationParameters            = new TokenValidationParameters
                {
                    ValidateAudience = false
                };
                // if token does not contain a dot, it is a reference token
                // https://leastprivilege.com/2020/07/06/flexible-access-token-validation-in-asp-net-core/
                options.ForwardDefaultSelector = Selector.ForwardReferenceToken("introspection");
            })

            // reference tokens
            .AddOAuth2Introspection("introspection", options =>
            {
                options.Authority = oAuth2EndpointInfo.Url;

                options.ClientId     = oAuth2EndpointInfo.ClientId;
                options.ClientSecret = oAuth2EndpointInfo.ClientSecret;
            });

            services.AddControllers();
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            var clusterIdentityServer4Info = new IdentityServer4Info("https://*****:*****@3x3g*RLez$TNU!_7!QW", "Orleans");

            // ReSharper disable once RedundantTypeArgumentsOfMethod
            services.AddSingleton <IClusterClient>(serviceProvider =>
            {
                OrleansClusterClientProvider.StartClientWithRetries(out var client,
                                                                    serviceProvider.GetService <IHttpContextAccessor>(), clusterIdentityServer4Info);

                return(client);
            });
        }
コード例 #8
0
        private static async Task <IHost> StartSilo()
        {
            //var identityServer4Info = new IdentityServer4Info("https://*****:*****@3x3g*RLez$TNU!_7!QW", "Orleans");

            var identityServer4Info = new IdentityServer4Info("http://*****:*****@"TFGB=?Gf3UvH+Uqfu_5p", "Orleans");

            var builder = new HostBuilder()
                          .UseEnvironment(Environments.Development)
                          .UseOrleans((context, siloBuilder) =>
            {
                siloBuilder
                // Use localhost clustering for a single local silo
                .UseLocalhostClustering()
                // Configure ClusterId and ServiceId
                .Configure <ClusterOptions>(options =>
                {
                    options.ClusterId = "Orleans.Security.Test";
                    options.ServiceId = "ServiceId1";
                })
                // Configure connectivity
                .Configure <EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback)
                .ConfigureApplicationParts(parts =>
                                           parts.AddApplicationPart(typeof(UserGrain).Assembly).WithReferences())
                .ConfigureServices(services =>
                {
                    services.AddOrleansClusteringAuthorization(identityServer4Info,
                                                               config =>
                    {
                        config.ConfigureAuthorizationOptions = AuthorizationConfig.ConfigureOptions;
                        config.TracingEnabled = true;
                    });
                });
            })
                          // Configure logging with any logging framework that supports Microsoft.Extensions.Logging.
                          // In this particular case it logs using the Microsoft.Extensions.Logging.Console package.
                          .ConfigureLogging(logging => logging.AddConsole());

            var host = builder.Build();
            await host.StartAsync();

            return(host);
        }
        // For the production usage.
        public static void AddOrleansClusteringAuthorization(this IServiceCollection services,
                                                             IdentityServer4Info identityServer4Info, Action <Configuration> configure)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (identityServer4Info == null)
            {
                throw new ArgumentNullException(nameof(identityServer4Info));
            }

            if (configure == null)
            {
                throw new ArgumentNullException(nameof(configure));
            }

            services.AddSingleton(identityServer4Info);
            services.AddSingleton <IIncomingGrainCallFilter, IncomingGrainCallAuthorizationFilter>();
            services.AddOrleansClusterSecurityServices(configure);
        }
コード例 #10
0
        private static IClusterClient TryToConnect(IHttpContextAccessor httpContextAccessor,
                                                   IdentityServer4Info identityServer4Info)
        {
            var attempt = 0;

            //var logger = loggerFactory.CreateLogger<OrleansClusterClientProvider>();

            while (true)
            {
                try
                {
                    var client = Build(httpContextAccessor, identityServer4Info);
                    client.Connect().Wait();

                    //logger.LogInformation("Client successfully connect to silo host");

                    return(client);
                }
                catch (AggregateException ex)
                {
                    if (ex.InnerException is SiloUnavailableException)
                    {
                        attempt++;
                        //logger.LogError(ex, ex.Message);

                        if (attempt > _initializeAttemptsBeforeFailing)
                        {
                            throw;
                        }

                        Task.Delay(TimeSpan.FromSeconds(1));
                    }

                    //logger.LogError(ex, ex.Message);
                }
            }
        }
コード例 #11
0
ファイル: Startup.cs プロジェクト: Async-Hub/Orleans.Security
        // 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)
        {
            var oAuth2EndpointInfo = new IdentityServer4Info("http://*****:*****@"TFGB=?Gf3UvH+Uqfu_5p", "Orleans");

            services.AddAuthentication("token")
            // JWT tokens
            .AddJwtBearer("token", options =>
            {
                // For development environments only. Do not use for production.
                options.RequireHttpsMetadata = false;

                options.Authority = oAuth2EndpointInfo.Url;
                options.Audience  = "Api1";
                options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
                options.TokenValidationParameters            = new TokenValidationParameters
                {
                    ValidateAudience = false
                };
                // if token does not contain a dot, it is a reference token
                // https://leastprivilege.com/2020/07/06/flexible-access-token-validation-in-asp-net-core/
                options.ForwardDefaultSelector = Selector.ForwardReferenceToken("introspection");
            })

            // reference tokens
            .AddOAuth2Introspection("introspection", options =>
            {
                options.Authority = oAuth2EndpointInfo.Url;

                options.ClientId     = oAuth2EndpointInfo.ClientId;
                options.ClientSecret = oAuth2EndpointInfo.ClientSecret;
            });

            services.AddControllers();
            services.AddHttpContextAccessor();
        }
コード例 #12
0
 public static void StartClientWithRetries(out IClusterClient client,
                                           IHttpContextAccessor httpContextAccessor, IdentityServer4Info identityServer4Info)
 {
     if (_client != null && _client.IsInitialized)
     {
         client = _client;
     }
     _client = TryToConnect(httpContextAccessor, identityServer4Info);
     client  = _client;
 }
コード例 #13
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)
        {
            //IdentityServer4 credentials. Do not use this for production!
            var apiIdentityServer4Info = new IdentityServer4Info(Config.IdentityServerUrl,
                                                                 "Api1", @"TFGB=?Gf3UvH+Uqfu_5p", "Cluster");
            var clusterIdentityServer4Info = new IdentityServer4Info(Config.IdentityServerUrl,
                                                                     "Cluster", "@3x3g*RLez$TNU!_7!QW", "Cluster");

            // Read Azure Storage connection string.
            var simpleClusterAzureStorageConnection =
                Environment.GetEnvironmentVariable(EnvironmentVariables.SimpleClusterAzureStorageConnection);

            services.AddAuthentication("token")
            // JWT tokens
            .AddJwtBearer("token", options =>
            {
                // For development environments only. Do not use for production.
                options.RequireHttpsMetadata = false;

                options.Authority = apiIdentityServer4Info.Url;
                options.Audience  = "Api1";
                options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
                options.TokenValidationParameters            = new TokenValidationParameters
                {
                    ValidateAudience = false
                };
                // if token does not contain a dot, it is a reference token
                // https://leastprivilege.com/2020/07/06/flexible-access-token-validation-in-asp-net-core/
                options.ForwardDefaultSelector = Selector.ForwardReferenceToken("introspection");
            })

            // reference tokens
            .AddOAuth2Introspection("introspection", options =>
            {
                options.Authority = apiIdentityServer4Info.Url;
                // For development environments only. Do not use for production.
                options.DiscoveryPolicy.RequireHttps = false;
                options.ClientId     = apiIdentityServer4Info.ClientId;
                options.ClientSecret = apiIdentityServer4Info.ClientSecret;
            });

            services.AddControllers();
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddHttpClient(OAuth2IntrospectionDefaults.BackChannelHttpClientName)
            .ConfigurePrimaryHttpMessageHandler(() => CreateHttpClientHandler(true));

            // ReSharper disable once RedundantTypeArgumentsOfMethod
            services.AddSingleton <IClusterClient>(serviceProvider =>
            {
                var logger          = serviceProvider.GetRequiredService <ILogger <IClusterClient> >();
                var telemetryClient = serviceProvider.GetRequiredService <TelemetryClient>();

                var provider = new OrleansClusterClientProvider(
                    serviceProvider.GetService <IHttpContextAccessor>(),
                    logger, apiIdentityServer4Info, simpleClusterAzureStorageConnection,
                    telemetryClient);

                provider.StartClientWithRetries(out var client);

                return(client);
            });
        }
コード例 #14
0
        private static async Task <IHost> StartSilo(string simpleClusterAzureStorageConnection)
        {
            var identityServer4Info = new IdentityServer4Info(Config.IdentityServerUrl,
                                                              "Api1", @"TFGB=?Gf3UvH+Uqfu_5p", "Cluster");

            var builder = new HostBuilder()
                          .UseEnvironment(Environments.Staging)
                          .ConfigureServices((hostContext, services) =>
            {
                services.AddSingleton <ITelemetryInitializer>(serviceProvider =>
                                                              TelemetryInitializer.SiloHostTelemetryInitializer);

                services.AddApplicationInsightsTelemetryWorkerService(options =>
                {
                    options.InstrumentationKey = Config.InstrumentationKey;
                });
            })
                          .UseOrleans((context, siloBuilder) =>
            {
                siloBuilder
#if DEBUG
                .UseLocalhostClustering()
#else
                .UseAzureStorageClustering(options =>
                {
                    options.ConnectionString = simpleClusterAzureStorageConnection;
                })
                .Configure <SiloOptions>(options => options.SiloName = Config.SiloHostName)
                .Configure <ClusterMembershipOptions>(options =>
                {
                    options.NumVotesForDeathDeclaration = 1;
                    options.TableRefreshTimeout         = TimeSpan.FromSeconds(5);
                    options.DeathVoteExpirationTimeout  = TimeSpan.FromSeconds(5);
                    options.IAmAliveTablePublishTimeout = TimeSpan.FromSeconds(3);
                })
#endif
                // Configure ClusterId and ServiceId
                .Configure <ClusterOptions>(options =>
                {
                    options.ClusterId = "Orleans.Security.Test";
                    options.ServiceId = "ServiceId1";
                })
#if !DEBUG
                .ConfigureEndpoints(Dns.GetHostName(), siloPort:
                                    Config.SiloHostSiloPort, gatewayPort: Config.SiloHostGatewayPort)
#endif
                .ConfigureApplicationParts(parts =>
                                           parts.AddApplicationPart(typeof(UserGrain).Assembly).WithReferences())
                .ConfigureServices(services =>
                {
                    services.AddOrleansClusteringAuthorization(identityServer4Info,
                                                               config =>
                    {
                        config.ConfigureAuthorizationOptions = AuthorizationConfig.ConfigureOptions;
                        config.TracingEnabled           = true;
                        config.ConfigureSecurityOptions = options =>
                        {
                            //For not production environments only!
                            options.RequireHttps = false;
                        };
                    });
                });
            })
                          // Configure logging with any logging framework that supports Microsoft.Extensions.Logging.
                          // In this particular case it logs using the Microsoft.Extensions.Logging.Console package.
                          .ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.AddConsole();
            });

            var host   = builder.Build();
            var logger = host.Services.GetService <ILoggerFactory>().CreateLogger <ILogger>();

            HostInfo.Log(logger);

            await host.StartAsync();

            return(host);
        }