Asp.net core 2.0 mvc application get client ip address with load balancer option - asp.net-core

I am unable to get client IP address using .net core 2.0 application.
I used the below code in startup.cs file.
I used the below code in homecontriller.cs file.
I am getting remoteIpAddress is 1.0.0.0 in local. when I deployed in the server I got server IP address but I want to display the client IP address.
can you please help with this. thanks.
services.Configure<ForwardedHeadersOptions> (options => {
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor> ();
services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor> ();
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
app.UseForwardedHeaders(new ForwardedHeadersOptions {
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
}
public IActionResult Index() {
string remoteIpAddress = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
if (Request.Headers.ContainsKey("X-Forwarded-For")) {
remoteIpAddress = Request.Headers["X-Forwarded-For"];
}
ViewBag.ip1 = remoteIpAddress.ToString();
return View();
}

In project.json add a dependency to:
"Microsoft.AspNetCore.HttpOverrides": "1.0.0"
In Startup.cs, in the Configure() method add:
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto
});
and in controller
using Microsoft.AspNetCore.HttpOverrides;
then by this way you can get the IP address
Request.HttpContext.Connection.RemoteIpAddress

Related

"Issuer name does not match authority" error when using reverse proxy in front of SSL terminating load-balancer

I am trying to deploy our data API using APIgee proxy. The data API is using .NET Core 3.0 on an IIS server on AWS EC2 instance:
When I make a call to the data API using Apigee proxy I am getting this exception on the IIS server:
Category: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler
EventId: 0
RequestId: 80003dde-0002-fe00-b63f-84710c7967bb
RequestPath: /v0.1/wells/dpr
SpanId: |74716527-4b0a0a0f46d32af3.
TraceId: 74716527-4b0a0a0f46d32af3
ParentId:
Policy error while contacting the discovery endpoint https://example.com: Issuer name does not match authority: http://example.com
Exception:
System.InvalidOperationException: Policy error while contacting the discovery endpoint https://example.com: Issuer name does not match authority: http://example.com
at IdentityModel.AspNetCore.OAuth2Introspection.PostConfigureOAuth2IntrospectionOptions.GetIntrospectionEndpointFromDiscoveryDocument(OAuth2IntrospectionOptions options)
at IdentityModel.AspNetCore.OAuth2Introspection.PostConfigureOAuth2IntrospectionOptions.InitializeIntrospectionClient(OAuth2IntrospectionOptions options)
at IdentityModel.AspNetCore.OAuth2Introspection.OAuth2IntrospectionHandler.LoadClaimsForToken(String token)
at IdentityModel.AspNetCore.OAuth2Introspection.OAuth2IntrospectionHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler.HandleAuthenticateAsync()
From what I can see, the issue here is that the Loab-balancer is performing the SSL termination and making a call to the IIS server using HTTP and not HTTPS that is why the issuer name does not match. I have tried adding UseForwardedHeaders line to our .NET Core API:
public static IApplicationBuilder UseIdServer(this IApplicationBuilder app)
{
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseIdentityServer();
return app;
}
which is called here
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app
.UseCORS()
.UseCustomCookiePolicy(env)
.UseIdServer()
.UseRouting()
.UseAuth()
.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
However, that did not fix the issue.
Update 1:
I have also tried configuring the ForwardedHeaders like that in my startup.cs as suggested on the MS docs without success:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseForwardedHeaders();
...
}
Update 2
I tried overriding the request schema to https in the Configure method in Startup.cs as suggested in MS docs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Use((context, next) =>
{
context.Request.Scheme = "https";
return next();
});
...
}
That has resolved the issue. However, I am wondering how I can properly configure the X-Forwarded-* headers in the middleware.
Update 3
Thanks to #Chen who pointed me to resource which stated that I can configure the ForwardedHeaders in the Configure method like so
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedProto
});
...
}
Previously I tried the same but I used both ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto. For some reason, using just ForwardedHeaders.XForwardedProto resolved the issue.

EF Core to call database based on parameter in API

I have an API developed in .NET Core with EF Core. I have to serve multiple clients with different data(but the same schema). This is a school application, where every school want to keep their data separately due to competition etc. So we have a database for each school. Now my challenge is, based on some parameters, I want to change the connection string of my dbContext object.
for e.g., if I call api/students/1 it should get all the students from school 1 and so on. I am not sure whether there is a better method to do it in the configure services itself. But I should be able to pass SchoolId from my client application
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SchoolDataContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("APIConnectionString")));
services.AddScoped<IUnitOfWorkLearn, UnitOfWorkLearn>();
}
11 May 2021
namespace LearnNew
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//Comenting to implement Mr Brownes Solution
//services.AddDbContext<SchoolDataContext>(options =>
// options.UseSqlServer(
// Configuration.GetConnectionString("APIConnectionString")));
services.AddScoped<IUnitOfWorkLearn, UnitOfWorkLearn>();
services.AddControllers();
services.AddHttpContextAccessor();
services.AddDbContext<SchoolDataContext>((sp, options) =>
{
var requestContext = sp.GetRequiredService<HttpContext>();
var constr = GetConnectionStringFromRequestContext(requestContext);
options.UseSqlServer(constr, o => o.UseRelationalNulls());
});
ConfigureSharedKernelServices(services);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "LearnNew", Version = "v1" });
});
}
private string GetConnectionStringFromRequestContext(HttpContext requestContext)
{
//Trying to implement Mr Brownes Solution
var host = requestContext.Request.Host;
// Since I don't know how to get the connection string, I want to
//debug the host variable and see the possible way to get details of
//the host. Below line is temporary until the right method is identified
return Configuration.GetConnectionString("APIConnectionString");
}
private void ConfigureSharedKernelServices(IServiceCollection services)
{
ServiceProvider serviceProvider = services.BuildServiceProvider();
SchoolDataContext appDbContext = serviceProvider.GetService<SchoolDataContext>();
services.RegisterSharedKernel(appDbContext);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "LearnNew v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
You can access the HttpContext when configuring the DbContext like this:
services.AddControllers();
services.AddHttpContextAccessor();
services.AddDbContext<SchoolDataContext>((sp, options) =>
{
var requestContext = sp.GetRequiredService<IHttpContextAccessor>().HttpContext;
var constr = GetConnectionStringFromRequestContext(requestContext);
options.UseSqlServer(constr, o => o.UseRelationalNulls());
});
This code:
var requestContext = sp.GetRequiredService<IHttpContextAccessor>().HttpContext; var constr = GetConnectionStringFromRequestContext(requestContext);
options.UseSqlServer(constr, o => o.UseRelationalNulls());
will run for every request, configuring the connection string based on details from the HttpRequestContext.
If you need to use your DbContext on startup, don't resolve it through DI. Just configure a connection like this:
var ob = new DbContextOptionsBuilder<SchoolDataContext>();
var constr = "...";
ob.UseSqlServer(constr);
using (var db = new Db(ob.Options))
{
db.Database.EnsureCreated();
}
But in production you would normally create all your tenant databases ahead-of-time.

Problem in enabling CORS in asp net core web api v3.0

I am using asp net core 3.0 in my web API project. I have created various API's and all are accessible via Swagger or Postman. But when trying to access the same via any other client like React, Method not allowed (405 error code) is received. On investing further, I find out that at first, OPTION request is received from the React application and the net core web API application is giving the 405 status code. Further, I find out that I need to enable all the methods as well as origins from the net core application to accept all types of requests otherwise it will not accept OPTION request. To achieve this, I enabled CORS policy in startup.cs file but still had no luck. Following is my startup.cs file:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
var elasticUri = Configuration["ElasticConfiguration:Uri"];
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithExceptionDetails()
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elasticUri))
{
MinimumLogEventLevel = LogEventLevel.Verbose,
AutoRegisterTemplate = true,
})
.CreateLogger();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<IISServerOptions>(options =>
{
options.AutomaticAuthentication = false;
});
services.Configure<ApiBehaviorOptions>(options =>
{
//To handle ModelState Errors manually as ApiController attribute handles those automatically
//and return its own response.
options.SuppressModelStateInvalidFilter = true;
});
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddControllers(options =>
{
//To accept browser headers.
options.RespectBrowserAcceptHeader = true;
}).
AddNewtonsoftJson(options =>
{
// Use the default property (Pascal) casing
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
}).
AddJsonOptions(options =>
{
//Not applying any property naming policy
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.IgnoreNullValues = true;
}).
AddXmlSerializerFormatters().
AddXmlDataContractSerializerFormatters();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("CorsPolicy");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
//Configuring serilog
loggerFactory.AddSerilog();
}
}
I tried testing the same API with the OPTIONS method from POSTMAN. It is also giving the Http Status Code as 405. But when trying to access the same request using the POST method, I received the response successfully.
Is there anything wrong with the above code or something wrong with the order of middlewares being called in Configure().
Try to add extension method and modifying your startup class:
Extension method:
public static void AddApplicationError(this HttpResponse response, string
message)
{
response.Headers.Add("Application-Error", message);
response.Headers.Add("Access-Control-Expose-Headers", "Application-Error");
response.Headers.Add("Access-Control-Allow-Origin", "*");
}
Startup.cs :
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)
HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message);
}
});
});
}
P.S. in my case I had scenario also returning 405 status error, cause was, similar action methods I used and there are conflicted
For ex:
[HttpGet]
public ActionResult GetAllEmployees()
[HttpGet]
public ActionResult GetCustomers()
Hope this will help at least to show exact error message
You need to add Cors in Startup.cs file under your web api project
add this variable in Startup.cs
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
add services.AddCors before services.AddControllers() in the method ConfigureServices in file Startup.cs:
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:4000",
"http://www.yourdomain.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddControllers();
*** You can pass only * to allow all instead of passing http://localhost:4000","http://www.yourdomain.com in the WithOrigins method
add app.UseCors before app.UseAuthentication() in the method Configure in file Startup.cs:
app.UseCors(MyAllowSpecificOrigins);
Check this Microsoft help
Try this:
app.UseCors(policy =>
policy.WithOrigins("https://localhost:PORT", "https://localhost:PORT")
.AllowAnyMethod()
.WithHeaders(HeaderNames.ContentType)
);

Enable / Disable SSL on ASP.NET Core projects in Development

On an ASP.NET Core project, I am using SSL in Production so I have in Startup:
public void ConfigureServices(IServiceCollection services) {
services.AddMvc(x => {
x.Filters.Add(new RequireHttpsAttribute());
});
// Remaining code ...
}
public void Configure(IApplicationBuilder builder, IHostingEnvironment environment, ILoggerFactory logger, IApplicationLifetime lifetime) {
RewriteOptions rewriteOptions = new RewriteOptions();
rewriteOptions.AddRedirectToHttps();
builder.UseRewriter(rewriteOptions);
// Remaining code ...
}
It works fine in Production but not in Development. I would like to either:
Disable SSL in Development;
Make SSL work in Development because with current configuration it is not.
Do I need to set any PFX files on my local machine?
I am working on multiple projects so that might create problems?
You can configure a service using the IConfigureOptions<T> interface.
internal class ConfigureMvcOptions : IConfigureOptions<MvcOptions>
{
private readonly IHostingEnvironment _env;
public ConfigureMvcOptions(IHostingEnvironment env)
{
_env = env;
}
public void Configure(MvcOptions options)
{
if (_env.IsDevelopment())
{
options.SslPort = 44523;
}
else
{
options.Filters.Add(new RequireHttpsAttribute());
}
}
}
Then, add this class as a singleton:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
var builder = services.AddMvc();
services.AddSingleton<IConfigureOptions<MvcOptions>, ConfigureMvcOptions>();
}
Concerning the SSL point, you can easily use SSL using IIS Express (source)
If you don't want to use IIS Express then delete the https-address in Project Properties -> Debug section -> Under "Web Server Settings" -> Uncheck "Enable SSL".
just comment this line:
rewriteOptions.AddRedirectToHttps();
or in new versions of .Net core on Startup.cs comment:
app.UseHttpsRedirection();
Using #if !DEBUG, like below:
public void ConfigureServices(IServiceCollection services) {
services.AddMvc(x => {
#if !DEBUG
x.Filters.Add(new RequireHttpsAttribute());
#endif
});
// Remaining code ...
}

ASP.NET 5 beta8 app with virtual directories/applications

Since ASP.NET 5 beta8 we are experiencing problems using virtual directories and/or sub applications.
We want (for the time beeing) to serve images from a virtual directory or a "sub application". However we only get 404 errors when trying to use a virtual directory and 502.3 errors when using a "sub application".
The server is running IIS 8.0. The Application Pools for the site and the "sub application" is set to "No Managed Code".
Using the same configuration of virtual dirs/apps on another site running the "old" ASP.NET 4 version of our site works like expected.
The problem came after upgrading to beta8, so we assume it has something to do with the HttpPlatformHandler.
Are we missing something or is this a bug?
EDIT:
To clarify, the ASP.NET5 application works just fine. It is only the content from the virtual dirs/apps that cannot be accessed.
The HttpPlatformHandler is installed on the server.
Here is our current Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var builder = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.ConfigureXXXXXXIdentityServices(); // Custom identity implementation
services.AddMvc(options =>
{
options.OutputFormatters
.Add(new JsonOutputFormatter(new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}));
});
services.AddSqlServerCache(options =>
{
options.ConnectionString = "XXXXXX";
options.SchemaName = "dbo";
options.TableName = "AspNet5Sessions";
});
services.AddSession();
var builder = new ContainerBuilder();
builder.RegisterModule(new AutofacModule());
builder.Populate(services);
var container = builder.Build();
return container.Resolve<IServiceProvider>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.MinimumLevel = LogLevel.Debug;
loggerFactory.AddConsole();
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseFileServer(new FileServerOptions
{
RequestPath = new PathString("/gfx"),
FileProvider = new PhysicalFileProvider(#"\\webdata2.XXXXXX.se\webdata\gfx"),
EnableDirectoryBrowsing = false
});
app.UseFileServer(new FileServerOptions
{
RequestPath = new PathString("/files"),
FileProvider = new PhysicalFileProvider(#"\\webdata2.XXXXXX.se\webdata"),
EnableDirectoryBrowsing = false
});
}
else
{
app.UseExceptionHandler("/Error/Index");
}
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseIdentity();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
The app.UseFileServer() statements works on our dev machines, but cannot be used on the server, unless there is a way to specify credentials. (haven't found a way to do that... (yet...))
Got it "working".
Dropped all virtual directories and/or applications.
Changed the Application Pool user to a user that had rights to read the file shares on the other machine.
Added app.UseFileServer() to all environments for the required paths.
Feels like there should be an option to pass Network Credentials to the UseFileServer method...
The Hosting model changed in beta 8, meaning that you need to install the new HttpPlatformHandler module as an administrator.
See Change to IIS hosting model