Gravatar for
By Andres Aguiar

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • Microsoft Visual Studio 2015
  • .NET Framework 4.5.2
Show requirements

Install the Dependencies

Install Auth0 NancyFX dependency with NuGet

Install-Package Auth0.NancyFx.SelfHost

Configure Auth0

In your Nancy self-hosted application add the following to your BootStrapper:

protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
  // ...

  Auth0Authentication.Enable(pipelines, new AuthenticationConfig
    RedirectOnLoginFailed = "login",
    CookieName = "_auth0_userid",
    UserIdentifier = "userid"

  // ...

The RedirectOnLoginFailed specifies the view that should be shown to an authenticated user when they try to access a restricted view.

The CookieName allows you to set the name of the cookie that will be used to save the User information.

The UserIdentifier lets you set an identifier for the user. Currently, here are the fields that are available:

  • userid
  • email
  • nickname
  • gravatarurl

Auth0.Nancy.SelfHost enables CookieBasedSessions setting in the background. If you use this setting in your app as well, you should switch it off.

Add Auth0 Configuration

You need to configure your Auth0 keys in the app.config

    <!-- Auth0 configuration -->
    <add key="auth0:ClientId" value="YOUR_CLIENT_ID" />
    <add key="auth0:ClientSecret" value="YOUR_CLIENT_SECRET" />
    <add key="auth0:Domain" value="YOUR_AUTH0_DOMAIN" />
    <add key="auth0:CallbackUrl" value="https://YOUR_APP/callback" />

Block all Unauthenticated Requests

After you enabled the Auth0Authentication you are able to block all unauthenticated requests with the following code.

public class SecurePage : NancyModule
    public SecurePage()
        this.RequiresAuthentication(); //<- This is a new implemetation of default extension
        Get["/securepage"] = o => View["securepage"];

Add Auth0 Callback Handler

We need to add the handler for the Auth0 callback so that we can authenticate the user and get their information. We also need to add an endpoint to let users log in and log out.

public class Authentication : NancyModule
    public Authentication()
        Get["/login"] = o =>
            if (this.SessionIsAuthenticated())
                return Response.AsRedirect("securepage");

            var apiClient = new AuthenticationApiClient(ConfigurationManager.AppSettings["auth0:domain"]);
            var authorizationUri = apiClient.BuildAuthorizationUrl()
                .WithScope("openid profile")

            return Response.AsRedirect(authorizationUri.ToString());

        Get["/login-callback"] = o => this

        Get["/logout"] = o => this
Was this article helpful?
Use Auth0 for FREECreate free Account