Opening the Windows Firewall
If you're running Windows, then in order for your server to be accessible from outside of your local machine you'll need to open the Windows Firewall for your application. You can do this either from the Windows Defender UI or using code in your application. In both case, you will need elevated privledges (admin account) to make changes to the firewall.
#
Open Windows Firewall Via UIThese instructions are for Windows 10. For earlier versions of Windows, consult the documentation for specific steps.
Open the Windows Defender Firewall Control Panel module by running
control firewall.cpl
from the command line.On the left hand navigation, click on Allow an app or feature through Windows Defender Firewall to open the Allowed Apps dialog.
Click on the Change settings button to allow the settings to be changed. If you are not logged in to an admin account, you will be prompted for admin credentials.
Click on Allow another app... button to open the Add an app dialog. Click the Browse button to browse to your applications executable file, and select it.
- Click on the Add button to add allow the application access through the firewall.
#
Open Windows Firewall Via CodeThis requires accessing some COM references, which AFAIK can't be done in a class library. But you can easily add it to your application using the example below.
#
Add The COM ReferencesYou will first want to add two COM references to your application, hnetcfg.dll
and FirewallAPI.dll
. Both DLLs are located in C:\Windows\System32
directory.
In Visual Studio, right click on your project dependencies and select Add COM Reference.
Click the Browse button in the lower right hand corner of the dialog box.
Navigate to
C:\Windows\System32
and selecthnetcfg.dll
, then clicke the Add button.Repeat steps 2 and 3 for
FirewallAPI.dll
.Click OK in the dialog box to return to Visual Studio.
The COM references should now be added to your project.
#
Create a FirewallPolicy ClassNext we'll create a simple class that will create our firewall rule and policy. We'll include methods with matching delegate signatures for our server starting and stopping event handlers to add and remove the rule from the policy.
#
Add Middleware Extension MethodYou can add a middleware extension to handle adding and removing your policy.
In the example here, I use the IRestServer.AfterStarting
handler to add the policy because I don't want the firewall to be open to receiving messages until the server has finished starting up.
Likewise, I use the IRestServer.BeforeStopping
handler to remove the policy because I want to ensure no more requests are coming in before I begin shutting down the server.
#
Using Your Middleware ExtensionYou can now add your firewall policy to the server - make sure to do this before starting the server.