The web application starts by presenting an area that allows the user to select between various OpenID / OAuth providers. The following screenshot shows this area.
This provides a mechanism for the user to select one of the OpenId (OpenID, myOpenID, Google, Yahoo) or OAuth (Twitter) providers. Clicking on one of the providers starts the authentication process. Both OpenID and OAuth use a series of redirects to get the user authenticated. The key is that the authentication occurs on the provider’s site and that’s where the passwords are stored. Clicking one of the above providers results in a post to our application’s server. Our server then redirects to the provider’s server (after possible adding information to the post data). Here is a screenshot of the Twitter authentication page after the redirect to the Twitter provider.
Clicking the “Allow” button causes post to the Twitter servers and another redirect. This time back to our application’s server. This redirect includes information about you that is supplied by the OpenID / OAuth providers. At minimum the redirect supplies a ‘username’ back to the application.
Our application can then look up the ‘username’ in the database to determine if the user is allowed access. Users that are allowed access will have the above login area swapped out for a panel that provides access to features only available to authenticated users. The following screenshot is an example.
Now that we have covered the workflow, let’s take a look at some code. Since we have just looked at the presentation layer, let’s start with the ASP.NET MVC views.
The logic to display either the login screen or the panel with features for authenticated users is in the Master Page. The following code simply looks to determine if the user is authenticated. If not, it inserts the login partial view. Otherwise, it inserts in the panel partial view.
The above code inserts a ‘div’ containing two ‘spans’. The first ‘span’ is ‘floated left’ (via the CSS class left) and contains the user’s full name. The full name is stored in the ‘Session’ dictionary by the Controller (more later). The second ‘span’ is ‘floated right’ (via the CSS class right) and contains an unordered list of links that provide access to features available to authenticated users only. Be sure to mark these action methods with the ‘Authorize’ attribute otherwise users could directly navigate to the URL and access the feature.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<form id="openid-form" method="post" action="<%= Url.Action("OpenId", "Account") %>">
<p>Registered users can <strong>view and add private trucks</strong>. Otherwise feel free to browse
the <strong>public</strong> trucks in the list below.</p>
<p>Sign in using one of the providers below.</p>
<h3>Your OpendID Provider</h3>
<input name="openIdUrl" id="openIdUrl" type="text" />
<a id="signin">Sign In »</a>
The outer ‘div’ wraps a ‘form’ area that contains two child ‘div’ elements. The first child ‘div’ contains an unordered list of providers. This will be styled up using CSS and an image sprite to render the button images. The second child ‘div’ provides an ‘input’ text element that allows the user to enter the URL to any OpenID provider. The following CSS styles this partial view.
Before discussing the action methods of the controller, you will need to get the DotNetOpenAuth library. Once you download it add a reference to it from your web application project. If you want to get twitter connected up be sure to also download the ‘TwitterConsumer’ and ‘InMemoryTokenManager’ implementations. These implementations are C# code files that you will need to add to your project as well.
I have named the controller ‘AccountController’ and the following code shows the constructor and private fields.
The application uses Ninject as a dependency injection container (thus the missing parameterless controller constructor). Ninject will provide implementations of all the constructor parameters. References to these parameters are then tucked away into the ‘readonly’ fields.
The ‘OpenIdRelyingParty’ instance is an object implemented by the DotNetOpenAuth library that is used for the OpenID authentication. The ‘InMemoryTokenManager’ is used for OAuth authentication with Twitter. Before you can use Twitter as an OAuth provider, you must register your app with Twitter. As a result of this registration Twitter will issue a ‘consumerKey’ and a ‘consumerSecret’ to substitute as the ‘InMemoryTokenManager’ parameters.
public ActionResult OpenId(string openIdUrl)
var response = Openid.GetResponse();
if (response == null)
// User submitting Identifier
if (Identifier.TryParse(openIdUrl, out id))
var request = Openid.CreateRequest(openIdUrl);
var fetch = new FetchRequest();
catch (ProtocolException ex)
_logger.Error("OpenID Exception...", ex);
_logger.Info("OpenID Error...invalid url. url='" + openIdUrl + "'");
// OpenID Provider sending assertion response
var fetch = response.GetExtension<FetchResponse>();
string firstName = "unknown";
string lastName = "unknown";
string email = "unknown";
firstName = fetch.GetAttributeValue(WellKnownAttributes.Name.First);
lastName = fetch.GetAttributeValue(WellKnownAttributes.Name.Last);
email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
return CreateUser(response.ClaimedIdentifier, firstName, lastName, email);
_logger.Info("OpenID: Cancelled at provider.");
_logger.Error("OpenID Exception...", response.Exception);
This action method is called twice. The first time by our form being submitted by the user. The second time is a call back (redirect) from the OpenID provider. The first two lines of the method determine which stage we are in. The code inside the ‘if’ statement is executed when the user submits the form. This code creates an OpenID request and redirects to the OpenID provider. Notice that we are requesting first and last names along with an email address. If the user has configured their OpenID provider to share this info it will be available to us.
The OpenID provider then redirects their response back to our action method. This time, there will be a value for the ‘response’ The code inside the ‘switch’ statement processes that response. If the user is authenticated, the username, first & last name and email are send to the following ‘CreateUser’ action method.
This code checks to see if this user exists in the local database. If the user is not found, the ‘Create’ view is sent to the browser. This gives our application an opportunity to collect and validate the first & last name and email values. I will not show that view because it becomes application specific as to what additional information you collect from each user. I will also not show the action method that the ‘Create’ view posts back to.
If after the OpenID authentication the user was found in the database, the ‘username’ and ‘fullname’ are stored in the ‘Session’ cache, the user is signed in (cookie set) and a final redirect back to the ‘Index’ action method of the ‘Home’ page. This results in showing the panel that provides access to features only available to authenticated users.
The OAuth action methods are shown below. The ‘OAuth’ action method is called when the user submits the form. This uses the DotNetOpenAuth library to redirect (on the Channel.Send method) to the OAuth provider. Notice this code explicitly configures the callback URL.
public ActionResult OAuth(string returnUrl)
var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, TokenManager);
var callBackUrl = new Uri(Request.Url.Scheme + "://" + Request.Url.Authority + "/Account/OAuthCallback");
twitter.Channel.Send(twitter.PrepareRequestUserAuthorization(callBackUrl, null, null));
public ActionResult OAuthCallback()
var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, TokenManager);
var accessTokenResponse = twitter.ProcessUserAuthorization();
string userName = accessTokenResponse.ExtraData["screen_name"];
return CreateUser(userName, null, null, null);
_logger.Error("OAuth: No access token response!");
The OAuth provider then redirects to the specified callback URL (‘OAuthCallback’ in this case) where the response is processed. A similar process is followed as in the OpenID case. Authenticated responses use the ‘CreateUser’ action method (same as for OpenID and shown above).
Integrating OpenID and OAuth into your application is made very easy by using the DotNetOpenAuth library. There are a number of services popping up that provide a clean implementation of OpenID / OAuth authentication that you can pay to include in your project. The advantage is that they will maintain the compatibility with OpenID / OAuth as it evolves and are able to provide you statistics on access to your site. Otherwise, using the DotNetOpenAuth library and wiring things up your self is not that bad. If you find the DotNetOpenAuth library beneficial and if you feel so inclined to give back, they provide a way to donate on their page.