ASP.NET

Sample Project

Download this sample project configured with your Auth0 API Keys.

System Requirements
  • Microsoft Visual Studio 2015
  • Auth0-ASPNET v1.4.0
Show requirements

Install Auth0-ASPNET NuGet Package

Use the NuGet Package Manager (Tools -> Library Package Manager -> Package Manager Console) to install the Auth0-ASPNET package, running the command:

Install-Package Auth0-ASPNET

This package will add a LoginCallback.ashx to your project, which will process the login.

Configure Callback URLs

After authenticating the user on Auth0, we will do a POST to a URL on your web site. For security purposes, you have to register this URL on the Application Settings section on Auth0 Admin app.

http://localhost:PORT/LoginCallback.ashx

Filling Web.Config with your Auth0 Settings

The NuGet package also created three settings on <appSettings>. Replace those with the following settings:

<add key="auth0:ClientId" value="YOUR_CLIENT_ID" />
<add key="auth0:ClientSecret" value="YOUR_CLIENT_SECRET" />
<add key="auth0:Domain" value="YOUR_AUTH0_DOMAIN" />

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>

Accessing User Information

Once the user successfully authenticated to the application, a ClaimsPrincipal will be generated which can be accessed through the Current property:

public ActionResult Index()
{
  string email = ClaimsPrincipal.Current.FindFirst("email").Value;
}

The user profile is normalized regardless of where the user came from. We will always include these: user_id, name, email, nickname and picture. For more information about the user profile read this.

Further Reading

Authorization

You can use the usual authorization techniques since the LoginCallback.ashx handler and the Http Module will generate an IPrincipal on each request. This means you can use the declarative [Authorize] or <location path='..'> protection or code-based checks like User.Identity.IsAuthenticated

Redirecting to a Login Page

An [Authorize] attribute will generate a 401 - Unauthorized error if the request is not authenticated. If you want to redirect to a login page automatically in these cases, you can leverage the Forms Authentication module by configuring this in web.config:

<system.web>
  <authentication mode="Forms">
    <forms loginUrl="Account/Login" />
  </authentication>
</system.web>

In the above example, we are redirecting to a Login action in an Account controller. The Login action can return a view that integrates Lock or shows a custom UI, or directly redirect to Auth0 for authentication, as described in #4.

public ActionResult Login(string returnUrl)
{
  if (string.IsNullOrEmpty(returnUrl) || !this.Url.IsLocalUrl(returnUrl))
  {
    returnUrl = "/";
  }

  // you can use this for the 'authParams.state' parameter
  // in Lock, to provide a return URL after the authentication flow.
  ViewBag.State = "ru="+ HttpUtility.UrlEncode(returnUrl);

  return this.View();
}

Log Out

To clear the cookie generated on login, use the FederatedAuthentication.SessionAuthenticationModule.SignOut() method on the AccountController\Logout method.

A typical logout action on ASP.Net MVC would look like this:

public RedirectResult Logout()
{
  // Clear the session cookie
  FederatedAuthentication.SessionAuthenticationModule.SignOut();

  // Redirect to Auth0's logout endpoint
  var returnTo = Url.Action("Index", "Home", null, protocol: Request.Url.Scheme );
  return this.Redirect(
    string.Format(CultureInfo.InvariantCulture,
      "https://{0}/v2/logout?returnTo={1}",
      ConfigurationManager.AppSettings["auth0:Domain"],
      this.Server.UrlEncode(returnTo)));
}

Note that the final destination URL (the returnTo value) needs to be in the list of Allowed Logout URLs. Read more about this.

Linking Accounts

To allow users to link accounts from different providers, read Link Accounts.

You will need the access_token of the logged in user. You can get it from:

<%= ClaimsPrincipal.Current.FindFirst("access_token").Value %>

Flow the Identity to a WCF Service

If you want to flow the identity of the user logged in to a web site, to a WCF service or an API, you have to use the responseType: 'token' parameter on the login widget constructor. When sending that paramter, Auth0 will generate an id_token which is a JsonWebToken that can be either send straight to your service or it can be exchanged to generate an ActAs token. Read more about this.

Manage Environments: Dev, Test, Production

We recommend creating one application per environment in Auth0 and have different client ids and secret per environment. Read more about this.

Use Auth0 for FREECreate free Account