0

I have just created a .NET 8 API and I'm experiencing an error "System.ArgumentNullException: Value cannot be null. (Parameter 'uriString')" related to authentication when making calls to the endpoints. The parameters in launchSettings.json are correct. Initially, the error appeared when starting the API, but that part was resolved by adjusting the order of app.UseAuthentication() and app.UseAuthorization().

Error Details:

enter image description here

Controller:

enter image description here

Startup.js:

 public void ConfigureServices(IServiceCollection services)
 {

     services.AddAuthentication(AzureADB2CDefaults.JwtBearerAuthenticationScheme)
    .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));

     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

     services.AddAuthentication(AzureADB2CDefaults.JwtBearerAuthenticationScheme);

     //services.AddSingleton<IMemoryCache>(new MemoryCache(new MemoryCacheOptions() { SizeLimit = 102400 }));

     services.AddApiVersioning(o => o.ReportApiVersions = true);
     services.AddCors();

     services.AddControllersWithViews()
         .AddJsonOptions(options =>
         options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));

     services.AddAuthorizationBuilder();

     string dominio = Environment.GetEnvironmentVariable("AzureAdB2C:Domain", EnvironmentVariableTarget.Process);// Configuration.GetValue<string>("AzureAdB2C:Domain");
     string appuri = Environment.GetEnvironmentVariable("AzureAdB2C:ClientAppUri", EnvironmentVariableTarget.Process);  //Configuration.GetValue<string>("AzureAdB2C:ClientAppUri");
     string scope = Environment.GetEnvironmentVariable("AzureAdB2C:ScopeRead", EnvironmentVariableTarget.Process);  //Configuration.GetValue<string>("AzureAdB2C:ScopeRead");
     string loginMicrosoft = Environment.GetEnvironmentVariable("LoginMicrosoft", EnvironmentVariableTarget.Process);
     string authority = string.Format("https://{1}/{0}/oauth2/v2.0", dominio, loginMicrosoft);
     var uri = new Uri(authority + "/authorize");

     services.AddSwaggerGen(c =>
     {


         c.SwaggerDoc("1.0", new OpenApiInfo
         {
             Title = "Web Api Intercomunicador",
             Version = "1.0"
         });

         // Set the comments path for the Swagger JSON and UI.
         var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
         var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
         c.IncludeXmlComments(xmlPath);

         //AGREGADO PARA B2C



         c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
         {
             Type = SecuritySchemeType.OAuth2,
             Flows = new OpenApiOAuthFlows
             {
                 Implicit = new OpenApiOAuthFlow
                 {
                     AuthorizationUrl = uri,
                     Scopes = new Dictionary<string, string> {
                         { $"https://{dominio}/{appuri}/{scope}","API Acceso de lectura" }
                     }
                 }
             }
         });

         c.AddSecurityRequirement(
                 new OpenApiSecurityRequirement
                 {
                     {
                     new OpenApiSecurityScheme{
                         Reference = new OpenApiReference{
                             Id = "oauth2", //The name of the previously defined security scheme.
                             Type = ReferenceType.SecurityScheme
                         }
                     },
                     new []{ $"https://{dominio}/{appuri}/{scope}" }
                     }
         });

         c.OperationFilter<AssignOAuth2SecurityRequirements>();
     });


 }



 /// <summary>
 /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 /// </summary>
 /// <param name="app"></param>
 /// <param name="env"></param>
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     else
     {
         app.UseHsts();
     }

     app.UseSwagger();

     app.UseSwaggerUI(options =>
     {
         string policy = Environment.GetEnvironmentVariable("AzureAdB2C:SignUpSignInPolicyId", EnvironmentVariableTarget.Process);
         string clientId = Environment.GetEnvironmentVariable("AzureAdB2C:ClientSwaggerId", EnvironmentVariableTarget.Process);
         string appName = Environment.GetEnvironmentVariable("AzureAdB2C:AppName", EnvironmentVariableTarget.Process);

         options.SwaggerEndpoint("/swagger/1.0/swagger.json", "Web Api Intercomunicador");

         // var b2cConfig = Configuration.GetSection("b2c");

         // Datos para B2C
         options.OAuthAppName(appName);
         options.OAuthClientId(clientId);
         options.OAuthScopeSeparator(" ");
         options.OAuthAdditionalQueryStringParams(new Dictionary<string, string>() {
             { "p", policy }
         });
     });

     app.UseCors("CorsPolicy");
     app.UseHttpsRedirection();

     app.UseRouting();

     app.UseAuthentication();
     app.UseAuthorization();


     app.UseEndpoints(endpoints =>
     {
         endpoints.MapControllers();
     });

 }

I have just created a .NET 8 API and I'm experiencing an error "System.ArgumentNullException: Value cannot be null. (Parameter 'uriString')" related to authentication when making calls to the endpoints. The parameters in launchSettings.json are correct. Initially, the error appeared when starting the API, but that part was resolved by adjusting the order of app.UseAuthentication() and app.UseAuthorization().

What I Tried Verified Environment Variables: Checked that all required environment variables (AzureAdB2C:Domain, AzureAdB2C:SignUpSignInPolicyId, etc.) are set correctly and are not null or empty. Inspected launchSettings.json: Ensured that all the necessary parameters are correctly defined. Reviewed Startup Configuration: Adjusted the order of app.UseAuthentication() and app.UseAuthorization() in Startup.cs to ensure proper middleware setup. Checked Azure AD B2C Settings: Confirmed that all configurations in the Azure portal, including domain and policies, are properly defined and match the application's configuration. Added Logging: Implemented additional logging to trace where the uriString might be null. Expected Result I expected the API to authenticate requests successfully using Azure AD B2C without throwing any exceptions related to null URIs.

0

Browse other questions tagged or ask your own question.