ServiceStack

View on Github

ServiceStack

Community maintained

This tutorial demonstrates how to add user login to a ServiceStack web application. We recommend you to Log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it on Github.

View on Github
System requirements: Microsoft Visual Studio 2015 and up | .NET Framework 4.5.2

New to Auth? Learn How Auth0 works, how it integrates with Regular Web Applications and which protocol it uses.

Configure Auth0

Get Your Application Keys

When you signed up for Auth0, a new application was created for you, or you could have created a new one.

You will need some details about that application to communicate with Auth0. You can get these details from the Application Settings section in the Auth0 dashboard.

You need the following information:

  • Client ID
  • Domain

If you download the sample from the top of this page these details are filled out for you.

If you have more than one application in your account, the sample comes with the values for your Default App.

App Dashboard

Configure Callback URLs

A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated.

You need to whitelist the callback URL for your app in the Allowed Callback URLs field in your Application Settings. If you do not set any callback URL, your users will see a mismatch error when they log in.

If you are following along with the sample project you downloaded from the top of this page, you should set the Callback URL to http://localhost:6132/api/auth/auth0.

Create a ServiceStack application

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");
    }
}

Configure ServiceStack to use Auth0

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.

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.

Add the Authenticate Attribute to the Hello DTO:

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

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
}

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.

Trigger Authentication

You will need to redirect the user to the Auth0 Authorization endpoint in order to log in to the application. We will use the Auth0.NET SDK to construct the redirect URL. First, install the Auth0.AuthenticationApi NuGet package:

Install-Package Auth0.AuthenticationApi

Then, add an AccountController class to your MVC application with a Login action. This action will construct the authorization URL, and then redirect the user to that URL.

public class AccountController : Controller
{
    public ActionResult Login()
    {
        string clientId = WebConfigurationManager.AppSettings["oauth.auth0.AppId"];
        string domain = WebConfigurationManager.AppSettings["oauth.auth0.OAuthServerUrl"].Substring(8);

        var redirectUri = new UriBuilder(this.Request.Url.Scheme, this.Request.Url.Host, this.Request.Url.IsDefaultPort ? -1 : this.Request.Url.Port, "api/auth/auth0");

        var client = new AuthenticationApiClient(new Uri($"https://{domain}"));
        var authorizeUrlBuilder = client.BuildAuthorizationUrl()
            .WithClient(clientId)
            .WithRedirectUrl(redirectUri.ToString())
            .WithResponseType(AuthorizationResponseType.Code)
            .WithScope("openid profile")
            .WithAudience($"https://{domain}/userinfo");


        return Redirect(authorizeUrlBuilder.Build().ToString());
    }
}

Display User Information

Open default.htm and add a login button which will redirect the user to the /Account/Login route:

<div>
    <a class="btn" href="/Account/Login">Log In</a>
</div>

Also add the following statement in the jQuery.ready body which will call the /api/hello endpoint which will return the logged in user's information:

// 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>
Use Auth0 for FREE