ServiceStack.Net – Developing Authentication Module using Auth0 and OAuthProvider to login using GMail, Twitter, Facebook account


I know you might be asking yourself what is Service Stack. Service Stack is a high performance .NET Web Service Framework that simplifies the development of XML, JSON, JSV and SOAP Web Services. It is also an open source, cross platform Mono Web Service framework which supports running Web Services built with Service Stack to run in Windows environment with .NET code or in Linux environment with Mono support. Hence Service Stack is an ideal option if we plan to build Web Services in .NET and deploy in environment other than windows. Service Stack enforces convention-based DTO standards  to its Web Service interface. It is a simple, fast, lightweight, testable and clean Web Service framework which has been build on top of raw ASP.NET IHttpHandlers. Following is the architecture of Service Stack.

image

You can learn more about Service Stack from here  https://servicestack.net/. You can install ServiceStack.Net through Nuget package explorer and there are lot of packages available within ServiceStack.Net based on your requirement like Advanced HTML support for MVC application, Message Queue Server integration, JSON Serializers and many more. I recommend you to give a try with this framework because I feel it will help you while you are building an Enterprise Application. I will try to cover many areas and implementation of ServiceStack.Net through various posts.

Today I am going to try to use ServiceStack.Net for implementing User Authentication and Authorization feature in a Web application built on top of MVC 5. Let’s get going.

First I am going to create a blank MVC Application without any authentication process in VS 2013. Run your application to check it is working properly once the project is created. Just a kind of verification from your side. I always do that.

image

Cool, let’s now try to understand what are the types of Authentication Providers we are going to use here. We are going to use built-in Authentication Providers, OpenId Authentication Providers and OAuth2 Providers. The Open-Id and OAuth2 providers are for using Google, Twitter, LinkedIn and Facebook authentication.

Let us first install ServiceStack framework for MVC through Package Manager Console using the Nuget Command Install-Package ServiceStack.Host.Mvc

PM> Install-Package ServiceStack.Host.Mvc
Attempting to resolve dependency 'WebActivator (≥ 1.5)'.
Attempting to resolve dependency 'Microsoft.Web.Infrastructure (≥ 1.0.0.0)'.
Attempting to resolve dependency 'ServiceStack.Mvc (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Common (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Interfaces (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Text (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Client (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Server (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Redis (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.OrmLite (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.OrmLite.SqlServer (≥ 4.0.33)'.

Once ServiceStack is installed, we will find few changes in our Project.

image

There are few changes in Web.Config file. Below are the changes you can see.

image

image

Next in order to register ServiceStacks “/api” path we need to add the below code in RegisterRoutes() of RouteConfig.cs file

public static void RegisterRoutes(RouteCollection routes)
{
//This is required for Service Stack
routes.IgnoreRoute("api/{*pathInfo}");

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

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

Update your Index() action in HomeController with the following code

public ActionResult Index()
{
//return View();
return Redirect("default.htm");
}

ServiceStack supports authorizing as a client via Google, Facebook, Twitter OAuth Servers. To use this facility we have to install OAuthProvider using the Nuget command Install-Package Auth0-ServiceStack-OAuthProvider.

PM> Install-package Auth0-ServiceStack-OAuthProvider
Attempting to resolve dependency 'ServiceStack (≥ 3.9.28)'.
Attempting to resolve dependency 'ServiceStack.Common (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Interfaces (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Text (≥ 4.0.33)'.
Attempting to resolve dependency 'ServiceStack.Client (≥ 4.0.33)'.
Installing 'Auth0-ServiceStack-OAuthProvider 0.0.2'.
Successfully installed 'Auth0-ServiceStack-OAuthProvider 0.0.2'.
Adding 'Auth0-ServiceStack-OAuthProvider 0.0.2' to ServiceStack.WebAuth.Demo2.
Successfully added 'Auth0-ServiceStack-OAuthProvider 0.0.2' to ServiceStack.WebAuth.Demo2.

This installation will add two classes in App_Start folder (Auth0Provider and Auth0UserSession).

image

Oh no…! Everything was fine till then. The project was compiling properly. But as soon as I have installed the OAuthProvider, the whole project was giving me lot of build errors. Not knowing what to do I tried to seek various ways to resolve the issues but unfortunately no resolution was found. At last through one of the forum, I found I need to install ServiceStack of version 3.9.71 through Nuget.

Hence I Uninstalled all the packages ServiceStack, ServiceStack.Host.Mvc and Auth0.ServiceStack.OAuthProvider at first place. Cleaned the solution at earliest. Next I ran the following commands to install back these packages except OAuthProvider in specific version 3.9.71 through Nuget Command.

Install-Package ServiceStack -Version 3.9.71

Install-Package ServiceStack.Host.Mvc -Version 3.9.71

Install-Package Auth0-ServiceStack-OAuthProvider

Awesome now I am not getting any build errors and things are in place.

Now our next step is to enable Authentication and plug in Auth0’s provider. Let’s open the file AppHost.cs generated by ServiceStack and uncomment the following lines in Configure() Method.

image

Now update the method ConfigureAuth() with following lines of code as shown below.

image

Ok my final piece of code for ConfigureAuth() is here

/* Uncomment to enable ServiceStack Authentication and CustomUserSession*/
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"))
}));


//var appSettings = new AppSettings();

//Default route: /auth/{provider}
//Plugins.Add(new AuthFeature(() => new CustomUserSession(),
// new IAuthProvider[] {
// new CredentialsAuthProvider(appSettings),
// new FacebookAuthProvider(appSettings),
// new TwitterAuthProvider(appSettings),
// new BasicAuthProvider(appSettings),
// }));

//Default route: /register
//Plugins.Add(new RegistrationFeature());

//Requires ConnectionString configured in Web.Config
//var connectionString = ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString;
//container.Register<IDbConnectionFactory>(c =>
// new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider));

//container.Register<IUserAuthRepository>(c =>
// new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));

//var authRepo = (OrmLiteAuthRepository)container.Resolve<IUserAuthRepository>();
//authRepo.CreateMissingTables();
}

We are not doing any User Registration here, so we have commented out the lines required for User Registration

Well our next step is to register the OAuth Url in Application Settings section, since after authenticating the user on Auth0 we would do a POST to a URL on our web site. So let’s go ahead and modify our Web.Config accordingly.

image

Now here I will explain you what is required to be done. First create a free account of yours in https://auth0.com.

image

 image

image

Once your email is verified, next step is to select the type of App you are integrating Auth0. For me I have selected Regular Web App.

image

Then You will get a screen where you need to select the Platform we are using in the App. I am selecting ServiceStack.

image

Once selected, the next screen is going to provide you the three Auth0 parameters which are (oauth.auth0.AppId, oauth.auth0.AppSecret and oauth.auth0.OAuthServerUrl). Copy the values and paste them in the Web.Config file against the AppSettings keys you have specified.

Now copy this JavaScript code in your _Layout.cshtml file. The Auth0Lock parameter should have your oauth.auth0.AppId followed by oauth.auth0.OAuthServerUrl. You can get the values from your Web.Config file. Also the callbackUrl should have the port number if any is used for running your application

https://cdn.auth0.com/js/lock-6.2.min.js

var lock = new Auth0Lock('vs4n82A6wLrmViah2QW2IWM8pSV8mCbe', 'idevexplorer.auth0.com');

function signin() {
lock.show({
callbackURL: 'http://localhost:4678/api/auth/auth0/'
, responseType: 'code'
, authParams: {
scope: 'openid profile'
}
});
}

Now place a Sign In link in your Navigational Panel of _Layout.cshtml file


Once done run your application and click on the Sign In link. You will be able to see the following Auth0 popup window.

image

Hold on, things are done yet. Now we need to ensure that once the User is successful in login through Auth0 then all related information is available in our web application. So what we are going to do here is first login to Auth0  site and go to Settings section of Default app. Update the Callback URL of your application like http://localhost:4678/api/auth/auth0/ which is specified in you JavaScript block of SignIn() method

image

Now lets modify  our Index.cshtml by placing a div over the top which will be the placeholder of the information grabbed from Auth0.


User Info:
Not logged in

And then we are going to update our _Layout.cshtml file adding a script block to render “userInfo” code template with the data retrieved from the authentication module.

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

$(function () {
$.getJSON('/api/hello', function (data) {
$("#content").is(":hidden");
$('#userInfo').text(JSON.stringify(data.userInfo, 1, 2));
});
});

Great, let’s go ahead and now run the application. And then try to login through Goggle account. You can see the result as below which will be rendered in “userInfo code block

image

Try with various options for logging into the application. I hope you will like this article and this will provide a platform for you to start with  Auth0 authentication integration using ServiceStack in future.

6 thoughts on “ServiceStack.Net – Developing Authentication Module using Auth0 and OAuthProvider to login using GMail, Twitter, Facebook account

  1. Hi there! This article couldn’t be written much better! Going through this article reminds me of my previous roommate! He constantly kept preaching about this. I am going to forward this post to him. Pretty sure he will have a good read. Many thanks for sharing!

    Like

  2. Pingback: Here is the missing "Publish this Angular .NET MVC App" from the book I read - elbsolutions.com Project List & Blog

  3. What’s up to every one, because I am really eager of reading this weblog’s post to be updated on a regular basis. It includes good material.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s