ServiceStack

Download a sample project.

System Requirements

This tutorial and seed project have been tested with the following:

  • Microsoft Visual Studio 2015
  • .NET Framework 4.5.2

To follow along with this guide, sign up for your free Auth0 account

At the end of this tutorial you will have a working web site that calls a ServiceStack API with authenticated users.

Before you start

We assume you are familiar with ServiceStack

1. Create a simple MVC4 website and install ServiceStack through NuGet

For this example, we will use the standard template that ships with Visual Studio. Select "FILE -> New project -> ASP.NET Web Application -> MVC" .

Once the default template unfolds, use NuGet to install the ServiceStack.Host.Mvc nuget, running the command:

Install-Package ServiceStack.Host.Mvc

Add the following line to your App_Start/Route_Config.cs file to the beginning of the RegisterRoutes function (this is required for ServiceStack):

routes.IgnoreRoute("api/{*pathInfo}");

Change HomeController to return the default.htm page. Under the Controllers folder add:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return Redirect("default.htm");
    }
}

2. Install Auth0 OAuthProvider

We provide a Nuget package to simplify integration of Auth0 with ServiceStack based applications.

Run this command on the Package Manager Console:

Install-Package Auth0-ServiceStack-OAuthProvider

This command will add two classes to your project under the App_Start folder: Auth0Provider and Auth0UserSession.

Auth0Provider extends ServiceStack's OAuthProvider and handles the authentication transaction for you.

3. Enable Authentication and plug in Auth0's Provider

Open the AppHost.cs file (also under the App_Start folder) generated by the ServiceStack NuGet. Uncomment the following call under the Configure method:

ConfigureAuth(container);

And then uncomment (if it is commented out) and edit the ConfigureAuth method to look like this:

private void ConfigureAuth(Funq.Container container){
 var appSettings = new AppSettings();
 
 Plugins.Add(new AuthFeature(() => new Auth0UserSession(),
  new IAuthProvider[]
   {
     new Auth0Provider(appSettings, appSettings.GetString("oauth.auth0.OAuthServerUrl"))
   }));
}

In this sample we are not interested in user registration. So we are leaving that section out.

4. Setting up the callback URL in Auth0

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 (make sure to change the port).

http://localhost:PORT/api/auth/auth0/

5. Enter configuration settings

Open your web.config file and change the three Auth0's parameters under <appSettings>:

<add key="oauth.auth0.AppId" value="YOUR_CLIENT_ID" />
<add key="oauth.auth0.AppSecret" value="YOUR_CLIENT_SECRET" />
<add key="oauth.auth0.OAuthServerUrl" value="https://YOUR_NAMESPACE" />

6. Add backend code to test the app

Open the the WebServiceExamples.cs file.

6.1. Add the Authenticate attribute to the Hello DTO:

[Authenticate]
public class Hello
{
	public string Name { get; set; }
}

6.2. Add an IAuthSession property to the HelloResponse DTO:

public class HelloResponse
{
  public IAuthSession UserInfo { get; set; }
  public string Result { get; set; }
  public ResponseStatus ResponseStatus { get; set; } //Where Exceptions get auto-serialized
}

6.3. Modify the HelloService to return the currently logged in user's UserInfo object

public class HelloService : Service
{
  public object Any(Hello request)
  {
    IAuthSession session = this.GetSession();
    var sb = new StringBuilder();
    sb.AppendLine("Id: " + session.Id);
    sb.AppendLine("DisplayName: " + session.DisplayName);

    return new HelloResponse { Result = "Hello, " + request.Name, UserInfo = session };
  }
}

Notice we are not doing anything useful with these properties. You can place a breakpoint here and explore the session object.

7. Triggering login manually or integrating the Auth0Lock

For more information on using Lock see the documentation.

<script src="https://cdn.auth0.com/js/lock/10.2/lock.min.js"></script>
<script>
  var lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_NAMESPACE', {
    auth: {
      redirectUrl: 'http://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.2/lock.min.js"></script>
<script>
  var lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_NAMESPACE', {
    container: 'root',
    auth: {
      redirectUrl: 'http://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_NAMESPACE');
  function open() {
    lock.sms({
      callbackURL: 'http://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_NAMESPACE');
  function open() {
    lock.emailcode({
      callbackURL: 'http://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_NAMESPACE',
    clientID:       'YOUR_CLIENT_ID',
    callbackURL:    'http://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>

8. Add UI code to Login and invoke the HelloService

Open default.htm and add the following statement in the jQuery.ready body:

// get user info from hello endpoint
$.getJSON('/api/hello', function (data) {
    $('#userInfo').text(JSON.stringify(data.userInfo, 1, 2));
});

Add a section to display the UserInfo:

<div>User Info:
     <pre><code id="userInfo">Not logged in</code></pre>
</div>

9. Run the app

After successful authentication, the UserProfile will be displayed on the page.

Congratulations!

Try Auth0 for FREECreate free Account