NancyFX

Sample Project

Download this sample project 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 he tries 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. This are the fields that are available to use right now:

  • userid
  • email
  • nickname
  • gravatarurl

Important Hint: 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 his information. We also need to add an endpoint to let users Login and Logout

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

            return View["login"];
        };

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

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

Triggering Login Manually or Integrating Lock

For more information on using Lock see the documentation.

<script src="https://cdn.auth0.com/js/lock/10.6/lock.min.js"></script>
<script>
  var lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN', {
    auth: {
      redirectUrl: 'https://YOUR_APP/callback',
      responseType: 'code',
      params: {
        scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
      }
    }
  });
</script>
<button onclick="lock.show();">Login</button>
<div id="root" style="width: 320px; margin: 40px auto; padding: 10px; border-style: dashed; border-width: 1px; box-sizing: border-box;">
    embedded area
</div>
<script src="https://cdn.auth0.com/js/lock/10.6/lock.min.js"></script>
<script>
  var lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN', {
    container: 'root',
    auth: {
      redirectUrl: 'https://YOUR_APP/callback',
      responseType: 'code',
      params: {
        scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
      }
    }
  });
  lock.show();
</script>
<script src="https://cdn.auth0.com/js/lock-passwordless-2.2.min.js"></script>
<script>
  var lock = new Auth0LockPasswordless('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN');
  function open() {
    lock.sms({
      callbackURL: 'https://YOUR_APP/callback',
      authParams: {
        scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
      }
    });
  }
</script>
<button onclick="window.open();">SMS</button>
<script src="https://cdn.auth0.com/js/lock-passwordless-2.2.min.js"></script>
<script>
  var lock = new Auth0LockPasswordless('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN');
  function open() {
    lock.emailcode({
      callbackURL: 'https://YOUR_APP/callback',
      authParams: {
        scope: 'openid email'  // Learn about scopes: https://auth0.com/docs/scopes
      }
    });
  }
</script>
<button onclick="window.open();">Email Code</button>
<button class="signin-google">Sign in with Google (redirect)</button><br>
<button class="signin-google-popup">Sign in with Google (popup)</button><br>
<br><p>--- or ---</p>
<label>Email</label><input type="text" id="email"><br>
<label>Password</label><input type="password" id="password"><br>
<button class="signin-db">Sign in with Email/Password</button>

<script src="https://cdn.auth0.com/w2/auth0-7.1.min.js"></script>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
  var auth0 = new Auth0({
    domain:         'YOUR_AUTH0_DOMAIN',
    clientID:       'YOUR_CLIENT_ID',
    callbackURL:    'https://YOUR_APP/callback'
  });
  // sign-in with social provider with plain redirect
  $('.signin-google').on('click', function() {
    auth0.signin({connection: 'google-oauth2'}); // use connection identifier
  });
  // sign-in with social provider using a popup (window.open)
  $('.signin-google-popup').on('click', function() {
    auth0.signin({popup: true, connection: 'google-oauth2'},
                function(err, profile, id_token, access_token, state) {
                    /*
                      store the profile and id_token in a cookie or local storage
                        $.cookie('profile', profile);
                        $.cookie('id_token', id_token);
                    */
                });
  });
  $('.signin-db').on('click', function() {
    auth0.signin({
      connection: 'foo',
      username: 'bar',
      password: 'foobar'
    },
    function (err, profile, id_token, access_token, state) {
      /*
          store the profile and id_token in a cookie or local storage
            $.cookie('profile', profile);
            $.cookie('id_token', id_token);
        */
    });
  });
</script>

Note: Please note that the redirectUrl specified in the Auth0Lock constructor must match the one specified in the previous step

Use Auth0 for FREECreate free Account