I'm the founder of Hovgaard Games and developer of Startup Company: The Game.

Currently busy with the crowd translation platform: Localizor.

jhovgaard on Twitter

Enable CSRF Protection in Nancy

PUBLISHED 23 April, 2014 ()

What is CSRF?

Alright, I’ll make this quick since most of you will know this already.

CSRF stands for Cross-Site Request Forgery. What it bascially means is, that you make one website do a request to another website, without letting the user know.

To ensure that a request is coming from your own website, we have to push a unique string into a hidden input in every form that we post - this is called the AntiForgeryToken.

If you want to know more about CSRF go check out the Wikipedia page, it’s actually very well explained.

CSRF and Nancy

Like any other functionality in Nancy, you will not get a full blown plug-and-play solution. As always Nancy is all about lightweight and total freedom, so we have to make a little effort:

  1. Enable CSRF support in the Bootstrapper.
  2. Insert the AntiForgeryToken in every <form> element of our application.
  3. Validate the posted CSRF token using the built-in Nancy Helper method ValidateCsrfToken().
  4. Handle when Nancy can’t accept a given token (or if none is provided).

Alright let’s go.

1. Enable CSRF support

Create a NancyDefaultBootstrapper class or use your existing. Add the following line to your ApplicationStartup() method:


My bootstrapper now looks like this:

using Nancy;
using Nancy.Bootstrapper;
using Nancy.TinyIoc;

namespace NancyCsrfDemo
    public class Bootstrapper : DefaultNancyBootstrapper
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
            base.ApplicationStartup(container, pipelines);

Add the AntiForgeryToken to the form

Alright, you should already have some views in your application, one of them containing some form. In my example I’m using Razor as the viewengine.

To add the AntiForgeryToken to my form I simply add Html.AntiForgeryToken() to anywhere inside my <form> element.

My view looks like this:

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
        <h1>Welcome to Nancy CSRF Demo, @ViewBag.Name</h1>
        <form action="/" method="POST">
            <input type="text" name="name" value="@ViewBag.Name" />
            <input type="submit" />

The generated value of @Html.AntiForgeryToken() looks something like this (the string will change for each request):


Validate the posted token

When the user clicks my submit button their browser will send my application the value of the AntiForgeryToken/CSRF token. We need to handle this.

Nancy have a builtin method called ValidateCsrfToken(). The method will automatically lookup Request.Form.Ncsrf and throw a CsrfValidationException if the token is not valid.

The exception will end up showing a Error 500 page to the user, which isn’t fortunately. To overcome this we catch this exact exception and show some other result. Here’s my NancyModule:

using Nancy;
using Nancy.Security;

namespace NancyCsrfDemo
    public class HomeModule : NancyModule
        public HomeModule()
            Get["/"] = p =>
                return View["Index"];

            Post["/"] = p =>
                catch (CsrfValidationException)
                    return Response.AsText("Csrf Token not valid.").WithStatusCode(403);
                ViewBag.Name = Request.Form.Name;
                return View["Index"];

As you can I simply return a text response to the user, telling them the token is invalid. Also I’m returning a 403 Forbidden status code instead of 500 Internal Error. You may choose another solution :-)

Simple as that!

That is how CSRF protection works using Nancy. Please notice I’m not showing best practice here. You should move the try-catch into a BaseModule (maybe use the Before hook), there’s no need to copy/paste that code into every action of your application.

If I helped you out, please leave a comment, I love feedback :-)

The full example/demo is available at GitHub: https://github.com/jhovgaard/nancy-csrfdemo

Servant for IIS is now open-source!

PUBLISHED 9 September, 2013 ()

Servant for IIS on GitHub!

Wauw, happy days! This was a biggy! I’ve decided to completely open-source my number 1 pet project, Servant for IIS, under the MIT license. This means that you can jump right to https://github.com/jhovgaard/servant and check out the source. You can of course fork your own version, make it more awesome and send me your pull request!

I received a couple of questions regarding the open sourcing of Servant. I’ll share my answers here:

Was Servant initially meant to be monetized?

Absolutely! I wanted to make a Pro edition and earn some cash that way. Unfortunately for my economy it felt wrong. I’ve never shared anything but my blog posts with the community, even that I got so much from it. Making money out of my first real project just felt bad so I decided to open source it instead.

Does open sourcing Servant mean you’ll stop supporting and developing it?

Not at all. I’ll continue to support and develop Servant like I used to. The only difference is that you guys can help me make it go a lot faster! :-)

So that’s it! My first open-source project. I’m very excited about the future of Servant. I hope to see a lot of issues getting created and even some pull requests (that really would be awesome!).

Thanks for reading!


Servant 1.1 released

PUBLISHED 5 July, 2013 ()

At last, Servant 1.1 is now released and publicly available. The release of the first version was a very overwhelming experience. I received a lot of wonderful feedback from people who loved what Servant brought to the IIS. At the same time I was also taught that developers simply don’t accept bugs and glitches in production software. Servant 1.1 is all about that - bugfixes and performance improvements (boring stuff, I agree).

I’ll walk through the most exciting changes, starting with new features.

HTTPS support

I’m introducing HTTPS support for the Servant engine itself. That means that you’re now able to change the URL of Servant to for example https://servant.example.com. When Servant detects HTTPS in the entered URL a self-signed certificate will be created and installed on the server. You will see the nasty browser warning telling you that the site is not safe. That’s expected. To avoid it you would need to buy a SSL certificate for Servant. I don’t expect requests for this feature, but if you need it, please add/vote the idea at the UserVoice site.

Automatic error reporting and usage statistics

I had a hard time solving users’ problems. To overcome this, exceptions in Servant is now being sent to Raygun.io. Also all traffic is tracked using Google Analytics. Everything is totally anonymous.

For Google Analytics Servant uses IP Anonymization to hide your servers IP and disable cookieDomain to hide your hostname.

For error reporting Servant isn’t sending any personal data either. Reports are limited to machine informations (hardware, OS info), URL (without hostname) and the stacktrace of the thrown exception.

If you don’t like any data leaving your server you can disable it all under settings or during the installation.

Support for virtual applications

This is step 1/2 of the most requested feature for Servant: support for virtual applications under sites. A lot of people found Servant completely useless because their IIS setup was completely depending on virtual applications and directories. Applications are now supported. Directories is coming, I just need to figure out a smart way to visualize it.

Intelligent exception parsing

Servant now parses exception more intelligently. Instead of showing a huge list of HttpException for example, exceptions are now being parsed and the top exception message is shown. The message is gathered from the stacktrace’s first line, exactly how IIS shows errors.

IIS Default Web Site were missing

Yes, the biggest bug on Servant 1.0 has been fixed. A lot of users experienced that the site created by IIS on installation simply wasn’t available in Servant. It turned out that this site contained special protocol bindings such as net.tcp. Servant only supports HTTP/HTTPS. I’ve fixed it by ignoring all other protocols meaning the default web site is now available from Servant too. How could this get through the beta I ask myself…

So here you go, a stable release of Servant! The release includes a lot of additional bugfixes which isn’t mentioned in this post. Of course there will still be more bugs and glitches but hopefully few enough to overcome.

What about Servant 1.2, any new features?

What a great question! Servant 1.1 was in no doubt hard work, simply because it was boring (isn’t bugfixing always?). Developing Servant 1.2 is super fun, because it’s all about new features, great features actually.

The feature 1.2 will be remembered for is… Ready? Full blown totally automated full stack deployment! Yes! Servant will download your source from a Git repository, it will build your project, deploy it to not one but all of your Servant-enabled servers. It will even warm up each server using proxy (to support loadbalancing setups) and at last it rolls back the deploy if a server returns anything but 200 OK.

So that’s it for now. Go download Servant 1.1 and test it out yourself.

What do you think about this release? Are you excited about the upcoming deploy feature?

Have a great day!


Manage IIS from the browser

PUBLISHED 18 February, 2013 ()

I'm very proud to introduce you to my own very first product: Servant for IIS.

I daily administrate around 10 webservers. Each of these servers is forcing me to remote connect to the server or setup remote administration and install and configure both the client and server software. With different workstations I always end up hassling with VPN settings, client software etc. Personally I've never been a fan of "inetmgr", so I decided to stop whining and start contributing to my favorite webserver.

Servant for IIS is a completely hassle-free way to administrate your IIS directly from your web browser.

I'll start by showing you how to install it and then demonstrate its basic features.


  1. Go to www.servant.io and click the big green button to download the zip file.
  2. Login and copy the zip file to the server you want to install on.
  3. Extract all files from the zip to a desired folder. I'll go for C:\servant-1.0.1.
  4. Jump into the installation folder and double click the file Install Servant Service.bat. Servant will now install it self as a Windows Service called Servant for IIS. If you want to uninstall it again, simply run the file Uninstall Servant Service.bat. If this gives you any problems, try running "Servant.Server.exe install" from a command prompt as Administrator.
  5. A new browser window will automatically open. This is the installation wizard:
    URL of Servant is the URL you want Servant to be accessible from.
    Username and password is the credentials you want to use to authenticate yourself.
  6. When all fields is entered click the green button. This will save your configuration.
  7. The next screen leaves you only one button to click on: Click here to login now
  8. Servant will now ask for your credentials and log you in - That's it! You can now log out of your server and access Servant from your desktop machine.

The home screen

The home screen of Servant gives you a quick overview of the latest unhandled exceptions thrown by any of your sites. Clicking on the exception will redirect you to the details/stack trace of the selected exception (we will get to exceptions later).

Notice that all of your sites is available by clicking the Sites item in the menu to the left.

If you're experiencing bugs, want new features or anything else there's a feedback button to the right of the screen.

Create new site

By clicking on Create new under the menu's site section you'll be able to create a new website. Simply fill out all of the fields like when you create sites in the IIS Manager, and Servant will create the site and redirect you to the site's settings page. Simple as that!

Site settings

The site settings page give you direct access to the basic settings of a website.

You can change name, bindings, site path and application pool. Also you can start/stop a site, restart the site or recycle the application pool it's running on. Of course you can also delete the site.

From this screen you can go to the errors screen from the top menu.

Site settings

The site errors screen is powerful tool that quickly shows you all unhandled exceptions thrown by the selected website.

The exception column is the message of the exception.
The timestamp column is the time since the exception thrown. By hovering over the text you'll get the UTC timestamp.
By clicking on the exception message you'll be redirected to the error details screen.

That's all for now. Servant is not released as open source. There's a commercial edition on its way including awesome features like error monitoring, git publish and more.

I hope you like my product! I'm extremely excited about the release and would love to hear your feedback.

So please drop a comment, are you going to try out Servant on your servers?

Have a great day!

Deploying: Add Git support to your IIS server

PUBLISHED 12 July, 2012 ()

Have you heard?

Recently Microsoft bragged about the new and much more awesome Azure.

One of the more cool things they announced is the ability to deploy your applications directly from your git repository (using git push) and straight to your Azure hosted website. It loads your master branch, compiles everything and upload the whole thing automatically. Pretty sick!

Now you may think “Cool story bro, but I host my own IIS!” - Well, no problem! David Fowler and David Ebbo are the creators of Project Kudu - the engine behind automated deployment via Git on Azure. These guys did an awesome job by not limiting this project to Azure, making us able to use it on IIS. Now time to grok it!

Clone the repo

Point your browser to https://github.com/projectkudu/kudu and clone the master down to your disk.

Build n’ start!

Below I’ll assume that you have IIS 7.x installed on your local machine. If you want to go live with Kudu, simply deploy the Kudu.Web project to a site on your production/online IIS as usual.

Now open up the Kudu.sln in Visual Studio. Mark the Kudu.Web project as active (makes it bold) and hit CTRL+F5.

If everything went well you should now see the Kudu dashboard, looking like this:

Kudu Dashboard

Create your first Git enabled site

In your Kudu dashboard:

Kudu is now creating a brand new IIS site directly on your IIS (!!) and showing you some geeky stuff:

Kudu website created

It tells the URL to the Git remote we can push apps to, the URL to the site itself and the service URL which actually is the Git remote from before.

Let’s take a quick look in IIS to see what happend:

Kudu sites in IIS

So Kudu is creating 2 sites with a kudu_ prefix. The first is the main site, the one hosting your application. The second is the “git remote site”/service site. Both sites is running on the same application pool.

If we go to the application URL we see a default screen:

Kudu IIS default site

Let’s push it!

Alright, let’s assume that you want to push a FunnelWeb blog like mine to the newly created site. First clone your fork of FunnelWeb (or whatever application you like) to your disk. Next open up a git shell (if you’re using Github for Windows, go to the repository, select tools then open a shell here). We now need to add a new remote, using the Git URL we got from Kudu. In my case I typed this:

git remote add kudu http://localhost:63185/jhovgaardnet.git

Git now knows about the repository located on our local IIS, making us able to do a simple push of our master like this:

git push kudu master

Awesome! If you didn’t mess it up, this is what you should see (not necessary the dependency installations of course):

Now updating the application URL shows my fully deployed blog, just as expected. Yes, it’s freaking awesome!


The next thing for you will be to deploy Kudu on your production IIS, setting up sites as Kudu sites, setting correct bindings, etc.

I really think Kudu is swell and I hope to see some interesting forks of Kudu that moves it closer to a continuous integration system with Github hooks, unit testing abilities, etc. TeamCity is cool, but it’s expensive and heavy. We need a slick open source .NET alternative and I hope Kudu is the beginning!

What do you think? Can you see the possibilities? Are you going to use Kudu?

Thanks for reading guys!

If you read so far, why don’t you follow me on Twitter? :-)