Exemplo n.º 1
0
        public AuthMiddleware(
            // ReSharper disable once UnusedParameter.Local
            RequestDelegate requestDelegate, // Required by ASP.NET
            IConfigurationManager <OpenIdConnectConfiguration> openIdCfgMan,
            IClientAuthConfig config,
            ILogger log)
        {
            this.requestDelegate = requestDelegate;
            this.openIdCfgMan    = openIdCfgMan;
            this.config          = config;
            this.log             = log;
            this.authRequired    = config.AuthRequired;

            // This will show in development mode, or in case auth is turned off
            if (!this.authRequired)
            {
                this.log.Warn("### AUTHENTICATION IS DISABLED! ###", () => { });
                this.log.Warn("### AUTHENTICATION IS DISABLED! ###", () => { });
                this.log.Warn("### AUTHENTICATION IS DISABLED! ###", () => { });
            }
            else
            {
                this.log.Info("Auth config", () => new
                {
                    this.config.AuthType,
                    this.config.JwtIssuer,
                    this.config.JwtAudience,
                    this.config.JwtAllowedAlgos,
                    this.config.JwtClockSkew
                });

                this.tokenValidationParams = new TokenValidationParameters
                {
                    // Validate the token signature
                    RequireSignedTokens      = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKeys        = this.GetSigningKeys(),

                    // Validate the token issuer
                    ValidateIssuer = true,
                    ValidIssuer    = this.config.JwtIssuer,

                    // Validate the token audience
                    ValidateAudience = true,
                    ValidAudience    = this.config.JwtAudience,

                    // Validate token lifetime
                    ValidateLifetime = true,
                    ClockSkew        = this.config.JwtClockSkew
                };
            }

            // TODO ~devis: this is a temporary solution for public preview only
            // TODO ~devis: remove this approach and use the service to service authentication
            // https://github.com/Azure/pcs-auth-dotnet/issues/18
            // https://github.com/Azure/azure-iot-pcs-remote-monitoring-dotnet/issues/11
            this.log.Warn("### Service to service authentication is not available in public preview ###", () => { });
            this.log.Warn("### Service to service authentication is not available in public preview ###", () => { });
            this.log.Warn("### Service to service authentication is not available in public preview ###", () => { });
        }
Exemplo n.º 2
0
 public CorsSetup(
     IClientAuthConfig config,
     ILogger logger)
 {
     this.config = config;
     this.log    = logger;
 }
Exemplo n.º 3
0
        public Config(IConfigData configData)
        {
            this.Port = configData.GetInt(PORT_KEY);

            this.ServicesConfig = new ServicesConfig
            {
                StorageAdapterApiUrl   = configData.GetString(STORAGE_ADAPTER_URL_KEY),
                DeviceSimulationApiUrl = configData.GetString(DEVICE_SIMULATION_URL_KEY),
                TelemetryApiUrl        = configData.GetString(TELEMETRY_URL_KEY),
                SeedTemplate           = configData.GetString(SEED_TEMPLATE_KEY),
                AzureMapsKey           = configData.GetString(AZURE_MAPS_KEY)
            };

            this.ClientAuthConfig = new ClientAuthConfig
            {
                // By default CORS is disabled
                CorsWhitelist = configData.GetString(CORS_WHITELIST_KEY, string.Empty),
                // By default Auth is required
                AuthRequired = configData.GetBool(AUTH_REQUIRED_KEY, true),
                // By default auth type is JWT
                AuthType = configData.GetString(AUTH_TYPE_KEY, "JWT"),
                // By default the only trusted algorithms are RS256, RS384, RS512
                JwtAllowedAlgos = configData.GetString(JWT_ALGOS_KEY, "RS256,RS384,RS512").Split(','),
                JwtIssuer       = configData.GetString(JWT_ISSUER_KEY),
                JwtAudience     = configData.GetString(JWT_AUDIENCE_KEY),
                // By default the allowed clock skew is 2 minutes
                JwtClockSkew = TimeSpan.FromSeconds(configData.GetInt(JWT_CLOCK_SKEW_KEY, 120)),
            };
        }
Exemplo n.º 4
0
        public Config(IConfigData configData)
        {
            this.Port = configData.GetInt(PORT_KEY);

            this.ServicesConfig = new ServicesConfig
            {
                JwtUserIdFrom        = configData.GetString(JWT_USER_ID_FROM_KEY, "oid").Split(','),
                JwtNameFrom          = configData.GetString(JWT_NAME_FROM_KEY, "given_name,family_name").Split(','),
                JwtEmailFrom         = configData.GetString(JWT_EMAIL_FROM_KEY, "email").Split(','),
                JwtRolesFrom         = configData.GetString(JWT_ROLES_FROM_KEY, "roles"),
                PoliciesFolder       = MapRelativePath(configData.GetString(POLICIES_FOLDER_KEY)),
                AadEndpointUrl       = configData.GetString(AAD_ENDPOINT_URL, DEFAULT_AAD_ENDPOINT_URL),
                AadTenantId          = configData.GetString(AAD_TENANT_ID, String.Empty),
                AadApplicationId     = configData.GetString(AAD_APPLICATION_ID, String.Empty),
                AadApplicationSecret = configData.GetString(AAD_APPLICATION_SECRET, String.Empty),
                ArmEndpointUrl       = configData.GetString(ARM_ENDPOINT_URL, DEFAULT_ARM_ENDPOINT_URL),
            };

            this.ClientAuthConfig = new ClientAuthConfig
            {
                // By default CORS is disabled
                CorsWhitelist = configData.GetString(CORS_WHITELIST_KEY, string.Empty),
                // By default Auth is required
                AuthRequired = configData.GetBool(AUTH_REQUIRED_KEY, true),
                // By default auth type is JWT
                AuthType = configData.GetString(AUTH_TYPE_KEY, "JWT"),
                // By default the only trusted algorithms are RS256, RS384, RS512
                JwtAllowedAlgos = configData.GetString(JWT_ALGOS_KEY, "RS256,RS384,RS512").Split(','),
                JwtIssuer       = configData.GetString(JWT_ISSUER_KEY, String.Empty),
                JwtAudience     = configData.GetString(JWT_AUDIENCE_KEY, String.Empty),
                // By default the allowed clock skew is 2 minutes
                JwtClockSkew = TimeSpan.FromSeconds(configData.GetInt(JWT_CLOCK_SKEW_KEY, 120)),
            };
        }
Exemplo n.º 5
0
        public Config(IConfigData configData)
        {
            this.Port = configData.GetInt(PORT_KEY);

            this.ServicesConfig = new ServicesConfig
            {
                MessagesConfig = new StorageConfig(
                    configData.GetString(MESSAGES_DB_DATABASE_KEY),
                    configData.GetString(MESSAGES_DB_COLLECTION_KEY)),
                AlarmsConfig = new StorageConfig(
                    configData.GetString(ALARMS_DB_DATABASE_KEY),
                    configData.GetString(ALARMS_DB_COLLECTION_KEY)),
                StorageType              = configData.GetString(STORAGE_TYPE_KEY),
                DocumentDbConnString     = configData.GetString(DOCUMENTDB_CONNSTRING_KEY),
                DocumentDbThroughput     = configData.GetInt(DOCUMENTDB_RUS_KEY),
                StorageAdapterApiUrl     = configData.GetString(STORAGE_ADAPTER_API_URL_KEY),
                StorageAdapterApiTimeout = configData.GetInt(STORAGE_ADAPTER_API_TIMEOUT_KEY)
            };

            this.ClientAuthConfig = new ClientAuthConfig
            {
                // By default CORS is disabled
                CorsWhitelist = configData.GetString(CORS_WHITELIST_KEY, string.Empty),
                // By default Auth is required
                AuthRequired = configData.GetBool(AUTH_REQUIRED_KEY, true),
                // By default auth type is JWT
                AuthType = configData.GetString(AUTH_TYPE_KEY, "JWT"),
                // By default the only trusted algorithms are RS256, RS384, RS512
                JwtAllowedAlgos = configData.GetString(JWT_ALGOS_KEY, "RS256,RS384,RS512").Split(','),
                JwtIssuer       = configData.GetString(JWT_ISSUER_KEY, String.Empty),
                JwtAudience     = configData.GetString(JWT_AUDIENCE_KEY, String.Empty),
                // By default the allowed clock skew is 2 minutes
                JwtClockSkew = TimeSpan.FromSeconds(configData.GetInt(JWT_CLOCK_SKEW_KEY, 120)),
            };
        }
Exemplo n.º 6
0
        public Config(IConfigData configData)
        {
            this.Port = configData.GetInt(PORT_KEY);

            this.ServicesConfig = new ServicesConfig
            {
                JwtUserIdFrom = configData.GetString(JWT_USER_ID_FROM_KEY, "email").Split(','),
                JwtNameFrom   = configData.GetString(JWT_NAME_FROM_KEY, "email").Split(','),
                JwtEmailFrom  = configData.GetString(JWT_EMAIL_FROM_KEY, "email").Split(',')
            };

            this.ClientAuthConfig = new ClientAuthConfig
            {
                // By default CORS is disabled
                CorsWhitelist = configData.GetString(CORS_WHITELIST_KEY, string.Empty),
                // By default Auth is required
                AuthRequired = configData.GetBool(AUTH_REQUIRED_KEY, true),
                // By default auth type is JWT
                AuthType = configData.GetString(AUTH_TYPE_KEY, "JWT"),
                // By default the only trusted algorithms are RS256, RS384, RS512
                JwtAllowedAlgos = configData.GetString(JWT_ALGOS_KEY, "RS256,RS384,RS512").Split(','),
                JwtIssuer       = configData.GetString(JWT_ISSUER_KEY, String.Empty),
                JwtAudience     = configData.GetString(JWT_AUDIENCE_KEY, String.Empty),
                // By default the allowed clock skew is 2 minutes
                JwtClockSkew = TimeSpan.FromSeconds(configData.GetInt(JWT_CLOCK_SKEW_KEY, 120)),
            };
        }
 /// <summary>
 /// Create device code provider with callback
 /// </summary>
 /// <param name="config"></param>
 /// <param name="logger"></param>
 protected MsalPublicClientBase(IClientAuthConfig config, ILogger logger)
 {
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
     _config = config?.Query(AuthProvider.AzureAD)
               .Select(config => (config, CreatePublicClientApplication(config)))
               .ToList();
 }
Exemplo n.º 8
0
 /// <summary>
 /// Create auth provider. Need to also inject the http context accessor
 /// to be able to get at the http context here.
 /// </summary>
 /// <param name="ctx"></param>
 /// <param name="cache"></param>
 /// <param name="schemes"></param>
 /// <param name="config"></param>
 /// <param name="logger"></param>
 public MsalUserTokenClient(IHttpContextAccessor ctx, ICache cache,
                            IAuthenticationSchemeProvider schemes, IClientAuthConfig config, ILogger logger)
 {
     _schemes = schemes ?? throw new ArgumentNullException(nameof(schemes));
     _ctx     = ctx ?? throw new ArgumentNullException(nameof(ctx));
     _cache   = cache ?? throw new ArgumentNullException(nameof(cache));
     _logger  = logger ?? throw new ArgumentNullException(nameof(logger));
     _config  = config ?? throw new ArgumentNullException(nameof(config));
 }
 /// <inheritdoc/>
 public MsiAuthenticationClient(IClientAuthConfig config, ILogger logger) :
     base(logger)
 {
     _config = config?.Providers?
               .Where(c => c.Provider == AuthProvider.Msi)
               .Where(c => !string.IsNullOrEmpty(c.ClientId))
               .Select(CreateProvider)
               .ToList();
 }
Exemplo n.º 10
0
        public Config(IConfigData configData)
        {
            this.Port = configData.GetInt(PORT_KEY);

            this.ServicesConfig = new ServicesConfig
            {
                MessagesConfig = new StorageConfig(
                    configData.GetString(MESSAGES_DB_DATABASE_KEY),
                    configData.GetString(MESSAGES_DB_COLLECTION_KEY)),
                AlarmsConfig = new AlarmsConfig(
                    configData.GetString(ALARMS_DB_DATABASE_KEY),
                    configData.GetString(ALARMS_DB_COLLECTION_KEY),
                    configData.GetInt(ALARMS_DB_MAX_DELETE_RETRIES)),
                StorageType                     = configData.GetString(MESSAGES_STORAGE_TYPE),
                CosmosDbConnString              = configData.GetString(COSMOSDB_CONNSTRING_KEY),
                CosmosDbThroughput              = configData.GetInt(COSMOSDB_RUS_KEY),
                StorageAdapterApiUrl            = configData.GetString(STORAGE_ADAPTER_API_URL_KEY),
                StorageAdapterApiTimeout        = configData.GetInt(STORAGE_ADAPTER_API_TIMEOUT_KEY),
                UserManagementApiUrl            = configData.GetString(USER_MANAGEMENT_URL_KEY),
                TimeSeriesFqdn                  = configData.GetString(TIME_SERIES_FQDN),
                TimeSeriesAuthority             = configData.GetString(TIME_SERIES_AUTHORITY),
                TimeSeriesAudience              = configData.GetString(TIME_SERIES_AUDIENCE),
                TimeSeriesExplorerUrl           = configData.GetString(TIME_SERIES_EXPLORER_URL),
                TimeSertiesApiVersion           = configData.GetString(TIME_SERIES_API_VERSION),
                TimeSeriesTimeout               = configData.GetString(TIME_SERIES_TIMEOUT),
                ActiveDirectoryTenant           = configData.GetString(AAD_TENANT),
                ActiveDirectoryAppId            = configData.GetString(AAD_APP_ID),
                ActiveDirectoryAppSecret        = configData.GetString(AAD_APP_SECRET),
                DiagnosticsApiUrl               = configData.GetString(DIAGNOSTICS_URL_KEY),
                DiagnosticsMaxLogRetries        = configData.GetInt(DIAGNOSTICS_MAX_LOG_RETRIES),
                ActionsEventHubConnectionString = configData.GetString(ACTIONS_EVENTHUB_CONNSTRING),
                ActionsEventHubName             = configData.GetString(ACTIONS_EVENTHUB_NAME),
                LogicAppEndpointUrl             = configData.GetString(ACTIONS_LOGICAPP_ENDPOINTURL),
                BlobStorageConnectionString     = configData.GetString(ACTIONS_AZUREBLOB_CONNSTRING),
                ActionsBlobStorageContainer     = configData.GetString(ACTIONS_AZUREBLOB_CONTAINER),
                SolutionUrl                     = configData.GetString(SOLUTION_URL),
                TemplateFolder                  = AppContext.BaseDirectory + Path.DirectorySeparatorChar + configData.GetString(TEMPLATE_FOLDER)
            };

            this.ClientAuthConfig = new ClientAuthConfig
            {
                // By default CORS is disabled
                CorsWhitelist = configData.GetString(CORS_WHITELIST_KEY, string.Empty),
                // By default Auth is required
                AuthRequired = configData.GetBool(AUTH_REQUIRED_KEY, true),
                // By default auth type is JWT
                AuthType = configData.GetString(AUTH_TYPE_KEY, "JWT"),
                // By default the only trusted algorithms are RS256, RS384, RS512
                JwtAllowedAlgos = configData.GetString(JWT_ALGOS_KEY, "RS256,RS384,RS512").Split(','),
                JwtIssuer       = configData.GetString(JWT_ISSUER_KEY, String.Empty),
                JwtAudience     = configData.GetString(JWT_AUDIENCE_KEY, String.Empty),
                // By default the allowed clock skew is 2 minutes
                JwtClockSkew = TimeSpan.FromSeconds(configData.GetInt(JWT_CLOCK_SKEW_KEY, 120)),
                // By default the time to live for the OpenId connect token is 7 days
                OpenIdTimeToLive = TimeSpan.FromDays(configData.GetInt(OPEN_ID_TTL_KEY, 7))
            };
        }
 /// <inheritdoc/>
 public DevAuthenticationClient(IClientAuthConfig config, ILogger logger) :
     base(logger)
 {
     _config = config?.Providers?
               .Where(c => c.Provider == AuthProvider.Msi || c.Provider == AuthProvider.AzureAD)
               .Where(c => c.Audience != null && Regex.IsMatch(c.Audience, @"^[0-9a-zA-Z-.:/]+$"))
               .SelectMany(CreateProvider)
               .ToList();
 }
Exemplo n.º 12
0
 /// <inheritdoc/>
 public MsiAuthenticationClient(IClientAuthConfig config, ILogger logger) : base(logger)
 {
     _config = config?.Providers?
               .Where(c => c.Provider == AuthProvider.Msi)
               .Where(c => !string.IsNullOrEmpty(c.ClientId))
               .Select(c => CreateProvider(c, logger))
               .ToList();
     if (!_config.Any())
     {
         logger.Information("No managed service identity configured for this service.");
     }
 }
 /// <summary>
 /// Create token provider
 /// </summary>
 /// <param name="clock"></param>
 /// <param name="config"></param>
 /// <param name="oidc"></param>
 /// <param name="schemes"></param>
 /// <param name="ctx"></param>
 /// <param name="logger"></param>
 public OpenIdUserTokenClient(IClientAuthConfig config, IHttpContextAccessor ctx,
                              IOptionsMonitor <OpenIdConnectOptions> oidc, IAuthenticationSchemeProvider schemes,
                              ISystemClock clock, ILogger logger)
 {
     _clock   = clock ?? throw new ArgumentNullException(nameof(clock));
     _oidc    = oidc ?? throw new ArgumentNullException(nameof(oidc));
     _schemes = schemes ?? throw new ArgumentNullException(nameof(schemes));
     _ctx     = ctx ?? throw new ArgumentNullException(nameof(ctx));
     _logger  = logger ?? throw new ArgumentNullException(nameof(logger));
     _config  = config ?? throw new ArgumentNullException(nameof(config));
     Http     = new HttpClientFactory(logger.ForContext <HttpClientFactory>());
 }
Exemplo n.º 14
0
        public Config(IConfigData configData)
        {
            this.Port = configData.GetInt(PORT_KEY);

            var connstring = configData.GetString(IOTHUB_CONNSTRING_KEY);

            if (connstring.ToLowerInvariant().Contains("your azure iot hub"))
            {
                // In order to connect to Azure IoT Hub, the service requires a connection
                // string. The value can be found in the Azure Portal. For more information see
                // https://docs.microsoft.com/azure/iot-hub/iot-hub-csharp-csharp-getstarted
                // to find the connection string value.
                // The connection string can be stored in the 'appsettings.ini' configuration
                // file, or in the PCS_IOTHUB_CONNSTRING environment variable. When
                // working with VisualStudio, the environment variable can be set in the
                // WebService project settings, under the "Debug" tab.
                throw new Exception("The service configuration is incomplete. " +
                                    "Please provide your Azure IoT Hub connection string. " +
                                    "For more information, see the environment variables " +
                                    "used in project properties and the 'iothub_connstring' " +
                                    "value in the 'appsettings.ini' configuration file.");
            }

            this.ServicesConfig = new ServicesConfig
            {
                IoTHubConnString               = configData.GetString(IOTHUB_CONNSTRING_KEY),
                DevicePropertiesWhiteList      = configData.GetString(DEVICE_PROPERTIES_WHITELIST_KEY),
                DevicePropertiesTTL            = configData.GetInt(DEVICE_PROPERTIES_TTL_KEY),
                DevicePropertiesRebuildTimeout = configData.GetInt(DEVICE_PROPERTIES_REBUILD_TIMEOUT_KEY),
                StorageAdapterApiUrl           = configData.GetString(STORAGE_ADAPTER_URL_KEY),
                UserManagementApiUrl           = configData.GetString(USER_MANAGEMENT_URL_KEY)
            };

            this.ClientAuthConfig = new ClientAuthConfig
            {
                // By default CORS is disabled
                CorsWhitelist = configData.GetString(CORS_WHITELIST_KEY, string.Empty),
                // By default Auth is required
                AuthRequired = configData.GetBool(AUTH_REQUIRED_KEY, true),
                // By default auth type is JWT
                AuthType = configData.GetString(AUTH_TYPE_KEY, "JWT"),
                // By default the only trusted algorithms are RS256, RS384, RS512
                JwtAllowedAlgos = configData.GetString(JWT_ALGOS_KEY, "RS256,RS384,RS512").Split(','),
                JwtIssuer       = configData.GetString(JWT_ISSUER_KEY),
                JwtAudience     = configData.GetString(JWT_AUDIENCE_KEY),
                // By default the allowed clock skew is 2 minutes
                JwtClockSkew = TimeSpan.FromSeconds(configData.GetInt(JWT_CLOCK_SKEW_KEY, 120)),
                // By default the time to live for the OpenId connect token is 7 days
                OpenIdTimeToLive = TimeSpan.FromDays(configData.GetInt(OPEN_ID_TTL_KEY, 7))
            };
        }
Exemplo n.º 15
0
        public Config(IConfigData configData)
        {
            this.Port = configData.GetInt(PORT_KEY);

            this.ServicesConfig = new ServicesConfig
            {
                MessagesConfig = new StorageConfig(
                    configData.GetString(MESSAGES_DB_DATABASE_KEY),
                    configData.GetString(MESSAGES_DB_COLLECTION_KEY)),
                AlarmsConfig = new AlarmsConfig(
                    configData.GetString(ALARMS_DB_DATABASE_KEY),
                    configData.GetString(ALARMS_DB_COLLECTION_KEY),
                    configData.GetInt(ALARMS_DB_MAX_DELETE_RETRIES)),
                StorageType              = configData.GetString(MESSAGES_STORAGE_TYPE),
                CosmosDbConnString       = configData.GetString(COSMOSDB_CONNSTRING_KEY),
                CosmosDbThroughput       = configData.GetInt(COSMOSDB_RUS_KEY),
                StorageAdapterApiUrl     = configData.GetString(STORAGE_ADAPTER_API_URL_KEY),
                StorageAdapterApiTimeout = configData.GetInt(STORAGE_ADAPTER_API_TIMEOUT_KEY),
                UserManagementApiUrl     = configData.GetString(USER_MANAGEMENT_URL_KEY),
                TimeSeriesFqdn           = configData.GetString(TIME_SERIES_FQDN),
                TimeSeriesAuthority      = configData.GetString(TIME_SERIES_AUTHORITY),
                TimeSeriesAudience       = configData.GetString(TIME_SERIES_AUDIENCE),
                TimeSeriesExplorerUrl    = configData.GetString(TIME_SERIES_EXPLORER_URL),
                TimeSertiesApiVersion    = configData.GetString(TIME_SERIES_API_VERSION),
                TimeSeriesTimeout        = configData.GetString(TIME_SERIES_TIMEOUT),
                ActiveDirectoryTenant    = configData.GetString(AAD_TENANT),
                ActiveDirectoryAppId     = configData.GetString(AAD_APP_ID),
                ActiveDirectoryAppSecret = configData.GetString(AAD_APP_SECRET),
                DiagnosticsApiUrl        = configData.GetString(DIAGNOSTICS_URL_KEY),
                DiagnosticsMaxLogRetries = configData.GetInt(DIAGNOSTICS_MAX_LOG_RETRIES)
            };

            this.ClientAuthConfig = new ClientAuthConfig
            {
                // By default CORS is disabled
                CorsWhitelist = configData.GetString(CORS_WHITELIST_KEY, string.Empty),
                // By default Auth is required
                AuthRequired = configData.GetBool(AUTH_REQUIRED_KEY, true),
                // By default auth type is JWT
                AuthType = configData.GetString(AUTH_TYPE_KEY, "JWT"),
                // By default the only trusted algorithms are RS256, RS384, RS512
                JwtAllowedAlgos = configData.GetString(JWT_ALGOS_KEY, "RS256,RS384,RS512").Split(','),
                JwtIssuer       = configData.GetString(JWT_ISSUER_KEY, String.Empty),
                JwtAudience     = configData.GetString(JWT_AUDIENCE_KEY, String.Empty),
                // By default the allowed clock skew is 2 minutes
                JwtClockSkew = TimeSpan.FromSeconds(configData.GetInt(JWT_CLOCK_SKEW_KEY, 120)),
            };
        }
Exemplo n.º 16
0
        public AuthMiddleware(
            // ReSharper disable once UnusedParameter.Local
            RequestDelegate requestDelegate, // Required by ASP.NET
            IConfigurationManager <OpenIdConnectConfiguration> openIdCfgMan,
            IClientAuthConfig config,
            IUserManagementClient userManagementClient,
            ILogger log)
        {
            this.requestDelegate            = requestDelegate;
            this.openIdCfgMan               = openIdCfgMan;
            this.config                     = config;
            this.log                        = log;
            this.authRequired               = config.AuthRequired;
            this.tokenValidationInitialized = false;
            this.tokenValidationExpiration  = DateTime.UtcNow;
            this.userManagementClient       = userManagementClient;

            // This will show in development mode, or in case auth is turned off
            if (!this.authRequired)
            {
                this.log.Warn("### AUTHENTICATION IS DISABLED! ###", () => { });
                this.log.Warn("### AUTHENTICATION IS DISABLED! ###", () => { });
                this.log.Warn("### AUTHENTICATION IS DISABLED! ###", () => { });
            }
            else
            {
                this.log.Info("Auth config", () => new
                {
                    this.config.AuthType,
                    this.config.JwtIssuer,
                    this.config.JwtAudience,
                    this.config.JwtAllowedAlgos,
                    this.config.JwtClockSkew,
                    this.config.OpenIdTimeToLive
                });

                this.InitializeTokenValidationAsync(CancellationToken.None).Wait();
            }

            // TODO ~devis: this is a temporary solution for public preview only
            // TODO ~devis: remove this approach and use the service to service authentication
            // https://github.com/Azure/pcs-auth-dotnet/issues/18
            // https://github.com/Azure/azure-iot-pcs-remote-monitoring-dotnet/issues/11
            this.log.Warn("### Service to service authentication is not available in public preview ###", () => { });
            this.log.Warn("### Service to service authentication is not available in public preview ###", () => { });
            this.log.Warn("### Service to service authentication is not available in public preview ###", () => { });
        }
Exemplo n.º 17
0
        public Config(IConfigData configData)
        {
            this.Port = configData.GetInt(PORT_KEY);

            this.ServicesConfig = new ServicesConfig
            {
                StorageAdapterApiUrl   = configData.GetString(STORAGE_ADAPTER_URL_KEY),
                DeviceSimulationApiUrl = configData.GetString(DEVICE_SIMULATION_URL_KEY),
                TelemetryApiUrl        = configData.GetString(TELEMETRY_URL_KEY),
                SolutionType           = configData.GetString(SOLUTION_TYPE_KEY),
                SeedTemplate           = configData.GetString(SEED_TEMPLATE_KEY),
                AzureMapsKey           = configData.GetString(AZURE_MAPS_KEY),
                UserManagementApiUrl   = configData.GetString(USER_MANAGEMENT_URL_KEY),
                Office365LogicAppUrl   = configData.GetString(OFFICE365_LOGIC_APP_URL_KEY),
                ResourceGroup          = configData.GetString(RESOURCE_GROUP_KEY),
                SubscriptionId         = configData.GetString(SUBSCRIPTION_ID_KEY),
                ManagementApiVersion   = configData.GetString(MANAGEMENT_API_VERSION_KEY),
                ArmEndpointUrl         = configData.GetString(ARM_ENDPOINT_URL_KEY)
            };

            this.ClientAuthConfig = new ClientAuthConfig
            {
                // By default CORS is disabled
                CorsWhitelist = configData.GetString(CORS_WHITELIST_KEY, string.Empty),
                // By default Auth is required
                AuthRequired = configData.GetBool(AUTH_REQUIRED_KEY, true),
                // By default auth type is JWT
                AuthType = configData.GetString(AUTH_TYPE_KEY, "JWT"),
                // By default the only trusted algorithms are RS256, RS384, RS512
                JwtAllowedAlgos = configData.GetString(JWT_ALGOS_KEY, "RS256,RS384,RS512").Split(','),
                JwtIssuer       = configData.GetString(JWT_ISSUER_KEY),
                JwtAudience     = configData.GetString(JWT_AUDIENCE_KEY),
                // By default the allowed clock skew is 2 minutes
                JwtClockSkew = TimeSpan.FromSeconds(configData.GetInt(JWT_CLOCK_SKEW_KEY, 120)),
                // By default the time to live for the OpenId connect token is 7 days
                OpenIdTimeToLive = TimeSpan.FromDays(configData.GetInt(OPEN_ID_TTL_KEY, 7))
            };
        }
Exemplo n.º 18
0
 /// <summary>
 /// Create interactive token provider with callback
 /// </summary>
 /// <param name="config"></param>
 /// <param name="logger"></param>
 public MsalInteractiveClient(IClientAuthConfig config, ILogger logger) :
     base(config, logger)
 {
 }
Exemplo n.º 19
0
 /// <summary>
 /// Create console output device code based token provider
 /// </summary>
 /// <param name="config"></param>
 /// <param name="logger"></param>
 public ClientCredentialClient(IClientAuthConfig config, ILogger logger)
 {
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
     _config = config ?? throw new ArgumentNullException(nameof(config));
     Http    = new HttpClientFactory(logger.ForContext <HttpClientFactory>());
 }
Exemplo n.º 20
0
 /// <summary>
 /// Create auth provider. Need to also inject the http context accessor
 /// to be able to get at the http context here.
 /// </summary>
 /// <param name="ctx"></param>
 /// <param name="config"></param>
 public PassThroughBearerToken(IHttpContextAccessor ctx,
                               IClientAuthConfig config = null)
 {
     _providers = config?.Providers?.Select(s => s.Provider).Distinct().ToList();
     _ctx       = ctx ?? throw new ArgumentNullException(nameof(ctx));
 }
Exemplo n.º 21
0
 /// <summary>
 /// Create console output device code based token provider
 /// </summary>
 /// <param name="config"></param>
 /// <param name="logger"></param>
 public MsalDeviceCodeClient(IClientAuthConfig config, ILogger logger) :
     this(new ConsolePrompt(), config, logger)
 {
 }
Exemplo n.º 22
0
 /// <summary>
 /// Create device code provider with callback
 /// </summary>
 /// <param name="prompt"></param>
 /// <param name="config"></param>
 /// <param name="logger"></param>
 public MsalDeviceCodeClient(IDeviceCodePrompt prompt,
                             IClientAuthConfig config, ILogger logger) : base(config, logger)
 {
     _prompt = prompt ?? throw new ArgumentNullException(nameof(prompt));
 }