Have added the valid ip addresses to appsettings.json and created a .cs file Filters/ClientcheckpageFilter.cs and copied the code from website for this
Have then put code below in startup.cs
services.AddMvc(options =>
{
options.Filters.Add
(new ClientIdCheckPageFilter
(_loggerFactory, Configuration));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
However getting error below
Build FAILED.
Startup.cs(47,42): error CS0246: The type or namespace name 'ClientIdCheckPageFilter' could not be found (are you missing a using directive or an assembly reference?) [D:\RazorPage\RazorPageProj2.csproj]
Startup.cs(48,42): error CS0103: The name '_loggerFactory' does not exist in the current context [D:\RazorPage\RazorPageProj2.csproj]
0 Warning(s)
2 Error(s)
Tried putting using ClientIdCheckPageFilter in startup.cs and using RazorPageProj2.ClientIpAspNetCore;
(name of namespace for ClientIdCheckPageFilter but still not working.
Startup.cs(15,22): error CS0234: The type or namespace name 'ClientIpAspNetCore' does not exist in the namespace 'RazorPageProj2' (are you missing an assembly reference?) [D:\RazorPage\RazorPageProj2.csproj]
0 Warning(s)
1 Error(s)but still not working.
The error indicates you are missing a "using" statements at the top of the startup.cs and ClientIdCheckFilter. Placing the cursor over the compiler error generally shows a help graphic that will provide options for add the using statement.
I have tried this but still getting error if have using RazorPageProj2.ClientIdCheckPageFilter; and if don't have it
If have it get error
Startup.cs(50,53): error CS0234: The type or namespace name 'ClientIdCheckPageFilter' does not exist in the namespace 'Razorproj2' (are you missing an assembly reference?) [D:\RazorPage\RazorPageProj2.csproj]
Startup.cs(51,42): error CS0103: The name '_loggerFactory' does not exist in the current context [D:\RazorPage\RazorPageProj2.csproj]
0 Warning(s)
2 Error(s)
If don't have it get message
Startup.cs(51,42): error CS0103: The name '_loggerFactory' does not exist in the current context [D:\RazorPage\RazorPageProj2.csproj]
0 Warning(s)
1 Error(s)
startup.cs code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using RazorPageProj2.Models;
using Oracle.EntityFrameworkCore;
using Razorproj2.ClientIpAspNetCore;
using RazorPageProj2.ClientIdCheckPageFilter;
namespace RazorPageProj2
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
//services.AddAuthentication(IISDefaults.AuthenticationScheme); // added 01/10/2019 for ad username
}
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<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //orig 09/10/19
//added below 09/10/19
// services.AddScoped<Razorproj2.ClientIpAspNetCore>();
services.AddMvc(options =>
{
options.Filters.Add
(new ClientIdCheckPageFilter
(_loggerFactory, Configuration));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<RazorPageProj2Context>(options =>
//options.UseSqlServer(Configuration.GetConnectionString("RazorPageProj2Context")));
options.UseOracle(Configuration.GetConnectionString("DefaultConnection"), opt => opt.UseOracleSQLCompatibility("11"))); //reads conn string from appsettings.json
//added below 11/06
services.AddMvc().AddRazorPagesOptions(options =>
//{
options.Conventions.AddPageRoute("/MULTIPLES/index", ""));
// }
// end of addition 11/06
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc();
}
}
}
Clientidcheckpagefilter.cs below
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Net;
namespace Razorproj2.ClientIpAspNetCore
{
public class ClientIdCheckPageFilter : IPageFilter
{
private readonly ILogger _logger;
private readonly string _safelist;
public ClientIdCheckPageFilter
(ILoggerFactory loggerFactory, IConfiguration configuration)
{
_logger = loggerFactory.CreateLogger("ClientIdCheckPageFilter");
_safelist = configuration["AdminSafeList"];
}
public void OnPageHandlerExecuting(PageHandlerExecutingContext context)
{
var remoteIp = context.HttpContext.Connection.RemoteIpAddress;
_logger.LogInformation(
"Remote IpAddress: {RemoteIp}", remoteIp);
string[] ip = _safelist.Split(';');
var bytes = remoteIp.GetAddressBytes();
var badIp = true;
foreach (var address in ip)
{
var testIp = IPAddress.Parse(address);
if (testIp.GetAddressBytes().SequenceEqual(bytes))
{
badIp = false;
break;
}
}
if (badIp)
{
_logger.LogInformation(
"Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
context.Result = new StatusCodeResult(401);
return;
}
}
public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
{
}
public void OnPageHandlerSelected(PageHandlerSelectedContext context)
{
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using RazorPageProj2.Models;
using Oracle.EntityFrameworkCore;
using Razorproj2.ClientIpAspNetCore;
//using RazorPageProj2.ClientIdCheckPageFilter;
using Microsoft.Extensions.Logging;
namespace RazorPageProj2
{
public class Startup
{
///added 09/10/19
ILoggerFactory _loggerFactory;
public Startup(ILoggerFactory loggerFactory, IHostingEnvironment env)
{
_loggerFactory = loggerFactory;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
///end of add 09/10/19
public Startup(IConfiguration configuration)
{
Configuration = configuration;
//services.AddAuthentication(IISDefaults.AuthenticationScheme); // added 01/10/2019 for ad username
}
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<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //orig 09/10/19
//added below 09/10/19
// services.AddScoped<Razorproj2.ClientIpAspNetCore>();
services.AddMvc(options =>
{
options.Filters.Add
(new ClientIdCheckPageFilter
(_loggerFactory, Configuration));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<RazorPageProj2Context>(options =>
//options.UseSqlServer(Configuration.GetConnectionString("RazorPageProj2Context")));
options.UseOracle(Configuration.GetConnectionString("DefaultConnection"), opt => opt.UseOracleSQLCompatibility("11"))); //reads conn string from appsettings.json
//added below 11/06
services.AddMvc().AddRazorPagesOptions(options =>
//{
options.Conventions.AddPageRoute("/MULTIPLES/index", ""));
// }
// end of addition 11/06
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc();
}
}
}
Just to say looks like working now in respect that if ip address not in list no access and if so access.
However, in firefox when not a valid ip address not getting message back and in chrome get message below back
This page isn’t working
If the problem continues, contact the site owner.
<div id="error-information-popup-container" jstcache="0"> <div id="error-information-popup" jstcache="0"> <div id="error-information-popup-box" jstcache="0"> <div id="error-information-popup-content" jstcache="0"> <div class="error-code" jscontent="errorCode"
jstcache="18">HTTP ERROR 402</div> <div class="error-code" jscontent="errorCode" jstcache="18"></div> <div class="error-code" jscontent="errorCode" jstcache="18"></div> <div class="error-code" jscontent="errorCode" jstcache="18">Have changed clientidcheckpagefilter.cs
to try and show more maningful message - whilst shows 402 now rather than 401 no sign of message below.</div> <div class="error-code" jscontent="errorCode" jstcache="18"></div> <div class="error-code" jscontent="errorCode" jstcache="18">How can we customise
the error message shown to be more user friendly in chrome and to ensure actually appears in firefox?</div> <div class="error-code" jscontent="errorCode" jstcache="18"></div> <div class="error-code" jscontent="errorCode" jstcache="18">
if (badIp)
{
_logger.LogInformation(
" Please contact IT to add you ip address to list of valid ip addresses. Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
context.Result = new StatusCodeResult(402);
return;
tried this and shows message expected in debugger when run on localhost as expected when adjust the list of valid ip addresses to exclude localhost.
as per below.
ClientIdCheckPageFilter[0] Please contact IT team to add you ip address to list of valid ip addresses. Forbidden Request from Remote IP address: ::1 ,
However, when publish to server doesn't display this message on firefiox at all and on chrome just shows the 402 as in previous post.
Have tried below
if (badIp)
{
_logger.LogInformation(
" Please contact IT to add you ip address to list of valid ip addresses. Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
context.Result = new StatusCodeResult(402);
string valueString = "IT";
Console.WriteLine(valueString);
return;
}
I'm looking for best way to get a user friendly message output to browser if user attempts to access the site from an invalid ip address.
tried this and shows message expected in debugger when run on localhost as expected when adjust the list of valid ip addresses to exclude localhost.
And the IPs are???
poR
ClientIdCheckPageFilter[0] Please contact IT team to add you ip address to list of valid ip addresses. Forbidden Request from Remote IP address: ::1 ,
This is a standard loop back IP addresses. I assume the code is functioning as written but not how you expect. Perhaps take a few moments to review your code and mentally trace through this loop. What happens when the IP address is ::1.
foreach (var address in ip)
{
var testIp = IPAddress.Parse(address);
if (testIp.GetAddressBytes().SequenceEqual(bytes))
{
badIp = false;
break;
}
}
Also, it seems you have changed the code since the original post as the original post does not return a 402. Always show the latest code when asking for assistance.
How can we do this "just change to to return a 200 (ok) and the desired html message content in the response." ?
Changed to 200 and displays no message at all even in chrome.
The application is working in sense that only ip addresses on the
"AdminSafeList" are getting access and those not on list don't get access.
Tested with the localhost ip address and without it to check behaving as expected Issue is that for the ip addresses not on the AdminSafelist there is no message in firefox and in chrome if have 402 shows below.
This page isn’t working
If the problem continues, contact the site owner."
</div> </div>
if (badIp)
{
_logger.LogInformation(
" Please contact IT to add you ip address to list of valid ip addresses. Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
context.Result = new StatusCodeResult(402);
string valueString = "Please contact IT to determine if your IP address can be added for access";
Console.WriteLine(valueString);
return;
}
In the PageFilter , if you want to display your valueString on the page, you could not use the "Console.WriteLine()" , you could write like this:
if (badIp)
{
_logger.LogInformation(
" Please contact IT to add you ip address to list of valid ip addresses. Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
context.Result = new StatusCodeResult(402);
string valueString = "Please contact IT to determine if your IP address can be added for access";
context.HttpContext.Response.WriteAsync(valueString);
return;
}
Member
15 Points
84 Posts
Net core razor pages ip whitelisting
Oct 09, 2019 10:36 AM|poR|LINK
Hi,
Have a net core razor CRUD application and looking into possibility of restricting access to the website to certain i.p. adresses.
Have read https://docs.microsoft.com/en-us/aspnet/core/security/ip-safelist?view=aspnetcore-3.0
Have added the valid ip addresses to appsettings.json and created a .cs file Filters/ClientcheckpageFilter.cs and copied the code from website for this
Have then put code below in startup.cs
However getting error below
Build FAILED.
Startup.cs(47,42): error CS0246: The type or namespace name 'ClientIdCheckPageFilter' could not be found (are you missing a using directive or an assembly reference?) [D:\RazorPage\RazorPageProj2.csproj]
Startup.cs(48,42): error CS0103: The name '_loggerFactory' does not exist in the current context [D:\RazorPage\RazorPageProj2.csproj]
0 Warning(s)
2 Error(s)
Tried putting using ClientIdCheckPageFilter in startup.cs and using RazorPageProj2.ClientIpAspNetCore; (name of namespace for ClientIdCheckPageFilter but still not working.
Startup.cs(15,22): error CS0234: The type or namespace name 'ClientIpAspNetCore' does not exist in the namespace 'RazorPageProj2' (are you missing an assembly reference?) [D:\RazorPage\RazorPageProj2.csproj]
0 Warning(s)
1 Error(s)but still not working.
Any thoughts on how to resolve?
Thanks
All-Star
43721 Points
18706 Posts
Re: Net core razor pages ip whitelisting
Oct 09, 2019 10:54 AM|mgebhard|LINK
The error indicates you are missing a "using" statements at the top of the startup.cs and ClientIdCheckFilter. Placing the cursor over the compiler error generally shows a help graphic that will provide options for add the using statement.
Member
15 Points
84 Posts
Re: Net core razor pages ip whitelisting
Oct 09, 2019 11:11 AM|poR|LINK
Thanks for suggestion.
I have tried this but still getting error if have using RazorPageProj2.ClientIdCheckPageFilter; and if don't have it
If have it get error
Startup.cs(50,53): error CS0234: The type or namespace name 'ClientIdCheckPageFilter' does not exist in the namespace 'Razorproj2' (are you missing an assembly reference?) [D:\RazorPage\RazorPageProj2.csproj]
Startup.cs(51,42): error CS0103: The name '_loggerFactory' does not exist in the current context [D:\RazorPage\RazorPageProj2.csproj]
0 Warning(s)
2 Error(s)
If don't have it get message
Startup.cs(51,42): error CS0103: The name '_loggerFactory' does not exist in the current context [D:\RazorPage\RazorPageProj2.csproj]
0 Warning(s)
1 Error(s)
startup.cs code below
Clientidcheckpagefilter.cs below
How can we adapt this code to resolve?
Thanks
Member
15 Points
84 Posts
Re: Net core razor pages ip whitelisting
Oct 09, 2019 11:27 AM|poR|LINK
Hi,
Just to let you know managed to get it to compile
tutorial doesn't look to have code referring to ILoggerFactory _loggerFactory; but had a look in github in sample code and saw it and tried it.
At least now compiles however despite changing to invalid ip addresses allows us in.
<div> <div>{</div> <div> "AdminSafeList": "1.0.0.1;1.168.1.5",</div> <div> "Logging": {</div> <div> "LogLevel": {</div> <div> "Default": "Warning"</div> <div> }</div> <div> },</div> </div>changed startup.cs to below.
Member
15 Points
84 Posts
Re: Net core razor pages ip whitelisting
Oct 09, 2019 01:17 PM|poR|LINK
Hi,
Just to say looks like working now in respect that if ip address not in list no access and if so access.
However, in firefox when not a valid ip address not getting message back and in chrome get message below back
This page isn’t working
If the problem continues, contact the site owner.
<div id="error-information-popup-container" jstcache="0"> <div id="error-information-popup" jstcache="0"> <div id="error-information-popup-box" jstcache="0"> <div id="error-information-popup-content" jstcache="0"> <div class="error-code" jscontent="errorCode" jstcache="18">HTTP ERROR 402</div> <div class="error-code" jscontent="errorCode" jstcache="18"></div> <div class="error-code" jscontent="errorCode" jstcache="18"></div> <div class="error-code" jscontent="errorCode" jstcache="18">Have changed clientidcheckpagefilter.cs to try and show more maningful message - whilst shows 402 now rather than 401 no sign of message below.</div> <div class="error-code" jscontent="errorCode" jstcache="18"></div> <div class="error-code" jscontent="errorCode" jstcache="18">How can we customise the error message shown to be more user friendly in chrome and to ensure actually appears in firefox?</div> <div class="error-code" jscontent="errorCode" jstcache="18"></div> <div class="error-code" jscontent="errorCode" jstcache="18"> </div> <div class="error-code" jscontent="errorCode" jstcache="18"> <div> <div>Thanks</div> </div> </div> </div> </div> </div> </div>All-Star
43721 Points
18706 Posts
Re: Net core razor pages ip whitelisting
Oct 09, 2019 01:45 PM|mgebhard|LINK
Please take a few minutes out of your day and run your code through the debugger. Pay attention to this block.
Member
15 Points
84 Posts
Re: Net core razor pages ip whitelisting
Oct 09, 2019 01:55 PM|poR|LINK
Thanks for suggestion..
tried this and shows message expected in debugger when run on localhost as expected when adjust the list of valid ip addresses to exclude localhost.
as per below.
ClientIdCheckPageFilter[0] Please contact IT team to add you ip address to list of valid ip addresses. Forbidden Request from Remote IP address: ::1 ,
However, when publish to server doesn't display this message on firefiox at all and on chrome just shows the 402 as in previous post.
Have tried below
I'm looking for best way to get a user friendly message output to browser if user attempts to access the site from an invalid ip address.
How can this best be achieved?
All-Star
43721 Points
18706 Posts
Re: Net core razor pages ip whitelisting
Oct 09, 2019 02:07 PM|mgebhard|LINK
And the IPs are???
This is a standard loop back IP addresses. I assume the code is functioning as written but not how you expect. Perhaps take a few moments to review your code and mentally trace through this loop. What happens when the IP address is ::1.
Also, it seems you have changed the code since the original post as the original post does not return a 402. Always show the latest code when asking for assistance.
All-Star
53554 Points
13305 Posts
Re: Net core razor pages ip whitelisting
Oct 09, 2019 02:22 PM|bruce (sqlwork.com)|LINK
You code returns a 401.
just change to to return a 200 (ok) and the desired html message content in the response.
Member
15 Points
84 Posts
Re: Net core razor pages ip whitelisting
Oct 09, 2019 02:35 PM|poR|LINK
Hi All,
Thanks for suggestion
How can we do this "just change to to return a 200 (ok) and the desired html message content in the response." ?
Changed to 200 and displays no message at all even in chrome.
The application is working in sense that only ip addresses on the
"AdminSafeList" are getting access and those not on list don't get access.
Tested with the localhost ip address and without it to check behaving as expected Issue is that for the ip addresses not on the AdminSafelist there is no message in firefox and in chrome if have 402 shows below.
This page isn’t working
If the problem continues, contact the site owner."
</div> </div>
Member
160 Points
88 Posts
Re: Net core razor pages ip whitelisting
Oct 11, 2019 09:10 AM|Lewis Lu|LINK
Hi poR,
In the PageFilter , if you want to display your valueString on the page, you could not use the "Console.WriteLine()" , you could write like this:
if (badIp) { _logger.LogInformation( " Please contact IT to add you ip address to list of valid ip addresses. Forbidden Request from Remote IP address: {RemoteIp}", remoteIp); context.Result = new StatusCodeResult(402); string valueString = "Please contact IT to determine if your IP address can be added for access"; context.HttpContext.Response.WriteAsync(valueString); return; }
Best regards,
Lewis
Member
15 Points
84 Posts
Re: Net core razor pages ip whitelisting
Oct 11, 2019 09:32 AM|poR|LINK
Hi Lewis,
Thanks for excellent suggestion. Works when deploy exactly as expected. with friendly message to user.
Also just another question re the logger stuff - do you know name of file it writes lon information to and where this would be located by default?
Also - is there a way to wildcard valid ip addresses
Tried .* but gave an error message e.g if we wanted all ip addresses ending 10* to have access?