ServiceStack

Community maintained

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • Microsoft Visual Studio 2015
  • .NET Framework 4.5.2
Show requirements

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

Before Starting

We assume you are familiar with ServiceStack

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

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

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

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.

Enable Authentication and Plugin 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.

Configuring Callback URLs

After authenticating the user on Auth0, we will do a POST to a URL on your website. For security purposes, you have to register this URL on the Client Settings section on Auth0 Admin app (make sure to change the port).

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

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_AUTH0_DOMAIN" />

Add Backend Code to Test the App

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

Integrate auth0.js

<script src="https://cdn.auth0.com/js/auth0/8.7/auth0.min.js"></script> 
<script type="text/javascript">
  var webAuth = new auth0.WebAuth({
    domain: 'YOUR_AUTH0_DOMAIN',
    clientID: 'YOUR_CLIENT_ID',
    redirectUri: 'https://YOUR_APP/callback',
    audience: `https://YOUR_AUTH0_DOMAIN/userinfo`,
    responseType: 'code',
    scope: 'openid profile'
  });
</script>
<button onclick="webAuth.authorize();">Log On</button>

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>

Run the app

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

Use Auth0 for FREECreate free Account