skip to Main Content

The Client application makes double queries to a single resource on the server. The first frame has no authorization header and the second frame does. Unfortunately, after reading the first frame, the server does not get the second frame. How to handle it on the ASP.NET CORE 5 server?

Endpoint for testing.
value always = {} when i call from client, from postman everything is working

        [ApiExplorerSettings(IgnoreApi = true)]
        [HttpPost("Service")]
        public IActionResult GetHeader()
        {
            var value = HttpContext.Request.Headers["Authorization"];
            return Ok();
        }
        app.UseMiddleware<SerilogMiddleware>();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<NotificationHub>("/api/socket");
            endpoints.UseSoapEndpoint<SVPService.SVPServiceSoap>((options) =>
            {
                options.Path = "/Service.asmx";
                options.Binding = new BasicHttpBinding()
                {
                    TextEncoding = new UTF8Encoding(false),
                    Security = new BasicHttpSecurity()
                    {
                        Mode = BasicHttpSecurityMode.TransportCredentialOnly,
                        Transport = new HttpTransportSecurity() { ClientCredentialType = HttpClientCredentialType.Basic }
                    }
                };
                options.SoapSerializer = SoapSerializer.XmlSerializer;
            }).RequireAuthorization();
        });
        app.UseMvc();

Logged Request from client on node.js server to get headers.

First Request Headers
{
  'user-agent': 'Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.42000)',
  'content-type': 'text/xml; charset=utf-8',
  'content-length': '806',
  expect: '100-continue',
  connection: 'Keep-Alive'
}
Second Request Headers
{
  'user-agent': 'Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.42000)',
  'content-type': 'text/xml; charset=utf-8',
  authorization: 'Basic dGVzdG93ZV91c2VybmFtZTp0ZXN0b3dlX3Bhc3N3b3Jk',
  'content-length': '806',
  expect: '100-continue'
}

Its a my startup.cs file

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
            {
                builder
                    //.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials().SetIsOriginAllowed(hostName => true);
                
            }));
            
            services.AddQuartz();

            services.Configure<JwtAuthentication>(Configuration.GetSection("JwtAuthentication"));
            services.AddAuthentication("BasicAuthentication")
                .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);


            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "xxx",
                    Title = "xxx",
                    Description = "xxx",
                    Contact = new OpenApiContact
                    {
                        Name = "xxx",
                        Email = "xxx",
                        Url = new Uri("xxx"),
                    },
                });

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

            MapperConfiguration mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);

            services.AddSignalR().AddNewtonsoftJsonProtocol();
            services.AddSingleton<ITokenService, TokenService>();
            services.AddSingleton<IPasswordService, PasswordService>();
            services.AddSingleton<IUserProfile, UserProfile>();
            services.AddSingleton<IReceiptService, ReceiptService>();
            services.AddSingleton<ISend, Send>();
            services.AddSingleton<IEncryption, Encryption>();
            services.AddSingleton<ParkingTicketManagementServiceV3, TicketManagement>();
            services.AddScoped<SVPService.SVPServiceSoap, SVPServiceSoap>();
            services.AddScoped<IManageSVP, ManageSVP>();
            services.AddScoped<IStripeMethods, StripeMethods>();
            services.AddScoped<IManageSchedullerRecurringPayment, ManageSchedullerRecurringPayment>();
            services.AddRepository();
            services.AddSingleton<IAuthorizationHandler, DenyAnonymousAuthorizationRequirement>();

            services.AddMvc(options =>
            {
                options.InputFormatters.Insert(0, new RawJsonBodyInputFormatter());
                options.EnableEndpointRouting = false;

            })
            .SetCompatibilityVersion(CompatibilityVersion.Latest)
            .AddNewtonsoftJson(opt =>
            {
                opt.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new LowerCaseNamingStrategy() };
                opt.SerializerSettings.StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.Default;
                opt.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                opt.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
                opt.SerializerSettings.MaxDepth = null;
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
            services.AddSwaggerGenNewtonsoftSupport();

            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseFileServer(new FileServerOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "StaticFile")),
                RequestPath = "/staticfile"
            });

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

            app.UseReDoc(c =>
            {
                c.SpecUrl = "xxx";
                c.DocumentTitle = "xxx";
            });

            app.UseMiddleware<SerilogMiddleware>();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<NotificationHub>("/api/socket");
                endpoints.UseSoapEndpoint<SVPService.SVPServiceSoap>((options) =>
                {
                    options.Path = "/Service.asmx";
                    options.Binding = new BasicHttpBinding()
                    {
                        TextEncoding = new UTF8Encoding(false),
                        Security = new BasicHttpSecurity()
                        {
                            Mode = BasicHttpSecurityMode.TransportCredentialOnly,
                            Transport = new HttpTransportSecurity() { ClientCredentialType = HttpClientCredentialType.Basic }
                        }
                    };
                    options.SoapSerializer = SoapSerializer.XmlSerializer;
                }).RequireAuthorization();
            });
            app.UseMvc();
        }
    }

2

Answers


  1. Chosen as BEST ANSWER

    Yes, To answer my question the header was actually missing the WWW-Authenticate: Basic realm = header.


  2. Just check if the response has the correct headers

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search