NancyFX

View on Github

NancyFX

Community maintained

This tutorial demonstrates how to add user login to a Nancy FX application. We recommend you to Log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it on Github.

View on Github
System requirements: Microsoft Visual Studio 2015 and up | .NET Framework 4.5.2

New to Auth? Learn How Auth0 works, how it integrates with Regular Web Applications and which protocol it uses.

Configure Auth0

Get Your Application Keys

When you signed up for Auth0, a new application was created for you, or you could have created a new one.

Your will need some details about that application to communicate with Auth0. You can get these details from the Application Settings section in the Auth0 dashboard.

You need the following information:

  • Client ID
  • Domain

If you download the sample from the top of this page these details are filled out for you.

If you have more than one application in your account, the sample comes with the values for your Default App.

App Dashboard

Configure Callback URLs

A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated.

You need to whitelist the callback URL for your app in the Allowed Callback URLs field in your Application Settings. If you do not set any callback URL, your users will see a mismatch error when they log in.

If you are following along with the sample project you downloaded from the top of this page, you should set the Callback URL to http://localhost:3000/callback.

Configure your application to use Auth0

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

<appSettings>
    <!-- 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" />
</appSettings>

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()
                .WithClient(ConfigurationManager.AppSettings["auth0:ClientId"])
                .WithRedirectUrl(ConfigurationManager.AppSettings["auth0:CallbackUrl"])
                .WithResponseType(AuthorizationResponseType.Code)
                .WithScope("openid profile")
                .Build();

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

        Get["/login-callback"] = o => this
            .AuthenticateThisSession()
            .ThenRedirectTo("securepage");

        Get["/logout"] = o => this
            .RemoveAuthenticationFromThisSession()
            .ThenRedirectTo("index");
    }
}
Use Auth0 for FREE