Using Auth0 with ServiceStack

We provide a Nuget package to simplify integration of Auth0 with ServiceStack based applications. 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 MVC3 website and install ServiceStack through NuGet

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

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 Global.asax file (this is required for ServiceStack):

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

Add a 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

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 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.

3. 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/

4. 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" />

5. Add backend code to test the app

Open the the WebServiceExamples.cs file.

1. Add the Authenticate attribute to the Hello DTO:

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

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
}

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

public class HelloService : ServiceBase<Hello>
{
    protected override object Run(Hello request)
    {
        IAuthSession session = this.GetSession();
        var sb = new StringBuilder();
        sb.AppendLine("Id: " + session.Id);
        sb.AppendLine("DisplayName: " + session.DisplayName);

        var auth0Session = session as Auth0UserSession;
        var pic = auth0Session.ExtraData["picture"];

        return new HelloResponse { UserInfo = session };
    }
}

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

6. Triggering login manually or integrating the Auth0 widget

There are different ways of integrating Auth0 in your site. Below, some of them with a preview and a code snippet to copy paste.

This is how it will look on a browser...

Auth0 JavaScript libraries are Open Source: https://github.com/auth0/widget https://github.com/auth0/auth0.js

7. 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>

8. Run the app

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

Congratulations!