Getting started with anti-forgery tokens in NancyFX with razor views is pretty simple.

To start you need to enable csrf in application startup.

1
2
3
4
5
6
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
Csrf.Enable(pipelines);
base.ApplicationStartup(container, pipelines);
}

Now you need to create a token on the get request that returns the form

1
2
3
4
5
6
7
8
9
Get["/"] = x =>
{
this.CreateNewCsrfToken();
return View["Index"];
};
<!-- more -->

Now in your view you need to render the token

1
2
3
4
5
6
7
8
9
<form method="POST">
Username <input type="text" name="Username" />
<br />
Password <input name="Password" type="password" />
<br />
<input type="submit" value="Login" />
@Html.AntiForgeryToken()
</form>

Finally you need to authenticate the token on the post request

1
2
3
4
5
6
7
8
9
10
11
12
Post["/"] = x =>
{
try
{
this.ValidateCsrfToken();
}
catch (CsrfValidationException)
{
return Response.AsText("Csrf Token not valid.").WithStatusCode(403);
}
//do something
};