我发现马克G的参考链接非常有用。
我已经将中间件配置为
ForwardedHeadersOptions
X-Forwarded-For
X-Forwarded-Proto
Startup.ConfigureServices
.
这是我的
代码文件:
配置服务
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity<ApplicationUser>();
services.AddCors(options =>
{
options.AddPolicy("AllowClient",
builder => builder.WithOrigins("http://**.asyncsol.com", "http://*.asyncsol.com", "http://localhost:10761", "https://localhost:44335")
.AllowAnyHeader()
.AllowAnyMethod());
});
services.AddMvc();
/* The relevant part for Forwarded Headers */
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
// base-address of your identityserver
//options.Authority = "http://server.asyncsol.com/";
options.Authority = "http://localhost:52718/";
// name of the API resource
options.Audience = "api1";
options.RequireHttpsMetadata = false;
});
}
配置
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
/* The relevant part for Forwarded Headers */
app.UseForwardedHeaders();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.UseAuthentication();
app.UseCors("AllowAll");
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
public IEnumerable<string> Get()
{
string ip = Response.HttpContext.Connection.RemoteIpAddress.ToString();
//https://en.wikipedia.org/wiki/Localhost
//127.0.0.1 localhost
//::1 localhost
if (ip == "::1")
{
ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList[2].ToString();
}
return new string[] { ip.ToString() };
}
所以,如果我在本地主机环境中运行,它会显示我的IPv4系统IP地址。
如果我在azure上运行我的服务器,它会显示我的主机名/IP地址。
结论:
Forwarded Headers Middleware