Rate this post

DotNetOpenAuth Hosting – Integrating OpenAuth/OpenID With Your ASP.NET MVC Application

DotnetOpenAuth is a open source library that allows the developers to add the OpenId and OAuth capabilities to their ASP.NET Web Application. It allows the developers to include the OpenId support by just dragging and dropping a ASP.NET control to the Web Page.

What is OpenId?
OpenId is a single sign-on scheme – the idea is that you keep your login and profile information in one place so that you don’t have to login at every Web location and create new user credentials on each site. The idea of a single sign on isn’t new of course – lots of these things have been around over the years with the most remembered probably being Microsoft’s Passport/Windows Live ID (not that anybody likes Windows Live Id).

What is OAuth?
OAuth is the main protocol. It is stable and ready to be implemented. Libraries are already available for many popular platforms such as PHP, Rails, Python, .NET, C, and Perl. We expect most upcoming work to focus on implementations and the development of extensions to the protocol.

And now, this articles about Integrating OpenAuth/OpenID with your ASP.NET MVC application, for this tutorial I use ASP.NET MVC 4.0 and Visual Studio 2012.

Step 1: Create a new project

  1. Go to File
  2. New Project Web
  3. Empty Asp.Net MVC 4 Application

Step 2: Add the following libraries

  • Use Nuget to get the following packages
  • DotNetOpenAuth.AspNet
  • Microsoft.AspNet.Providers.Core
  • Microsoft.AspNet.Providers.LocalDb
  • Microsoft.AspNet.Membership.OpenAuth

Step 3: Change web.config to use formsauthentication

<authentication mode=”Forms”>
<forms loginUrl=”~/Auth/Logon” timeout=”2880″ />
</authentication>

Step 4: Adding AuthConfig
Add a new class called AuthConfig.cs to folder App_Start that class will contains the register functions for all services that we will integrate. Add the following code to AuthConfig.cs and don’t forget to get services Api keys from each service website

public static void RegisterAuth()
{
OAuthWebSecurity.RegisterMicrosoftClient(
clientId: “”,
clientSecret: “”);
OAuthWebSecurity.RegisterTwitterClient(
consumerKey: “”,
consumerSecret: “”);
OAuthWebSecurity.RegisterFacebookClient(
appId: “”,
appSecret: “”);
OAuthWebSecurity.RegisterGoogleClient();
OAuthWebSecurity.RegisterLinkedInClient(
consumerKey: “”,
consumerSecret: “”);
OAuthWebSecurity.RegisterYahooClient();
}

Register AuthConfig to application start Go to Global.asax and add the following line to Application_Start function

AuthConfig.RegisterAuth();

Step 5: Adding Login functionality
Add a new controller for Authentication functionality called it AuthController.cs
add Logon Action for login page

public ActionResult Logon()
{
return View(OAuthWebSecurity.RegisteredClientData);
}

as you can notice that we user OAuthWebSecurity.RegisteredClientData as a model that object will contain all registered services that we put at AuthConfig class. Add a markup for login page

@using Microsoft.Web.WebPages.OAuth;
@model ICollection<AuthenticationClientData>
//Add this inside body
<div>
@using (Html.BeginForm(“ExternalLogin”, “Auth”, new { ReturnUrl = ViewBag.ReturnUrl }))
{
@Html.AntiForgeryToken()
<p>
@foreach (AuthenticationClientData p in Model)
{
<button value=”@p.AuthenticationClient.ProviderName” title=”Log in using your @p.DisplayName account”>@p.DisplayName</button>
}
</p>
}
</div>

as you can notice that we are looping against the services that we already registered in a previous step each AuthenticationClientData represent a service so we create a button to call that service we are adding all the buttons inside single form that calling ExternalLogin action method. Add ActionMethod ExternalLogin

[HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public void ExternalLogin(string provider, string returnUrl)
{
OAuthWebSecurity.RequestAuthentication(provider, Url.Action(“ExternalLoginCallback”, new { ReturnUrl = returnUrl }));
}

We are using OAuthWebSecurity.RequestAuthentication this function is requesting the authentication from the requested provider service “Facebook – Twitter – etc.”

[AllowAnonymous] public ActionResult ExternalLoginCallback(string returnUrl = “”)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action(“ExternalLoginCallback”, new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return RedirectToAction(“ExternalLoginFailure”);
}
//if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
//{
// return RedirectToLocal(returnUrl);
//}
if (User.Identity.IsAuthenticated)
{
// If the current user is logged in add the new account
OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
return RedirectToLocal(returnUrl);
}
else
{
// User is new, ask for their desired membership name
string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
OAuthAccount oAuthAccount = new OAuthAccount(result.Provider, result.ProviderUserId)
return View(“ExternalLoginConfirmation”, new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(“Index”, “Home”);
}
}

We have to verify authentication to ensure that the account is successfully authenticated if not redirect users to ExternalLoginFailure action if user is authenticated then we are going to login user to the system using simple membership we are going to talk about that in later posts then check if the current user is logged in add the new account else user is new, ask for their desired membership name then redirect to ExternalLoginConfirmation action with user information at RegisterExternalLoginModel class

public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model)
{
return View(model);
}
RegisterExternalLoginModel
public class RegisterExternalLoginModel
{
[Required] [Display(Name = “User name”)] public string UserName { get; set; }
public string ExternalLoginData { get; set; }
}

and now run your program.

DotNetOpenAuth Hosting with ASPHostPortal.com

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch.

ASPHostPortal.com will now DotNetOpenAuth Hosting (extensions for ASP.NET (WebPages)) service on all of our hosting plans, starting at just $5.00/mo! We offer completely Windows ASP.NET website hosting that is fast, reliable and packed with fantastic features to publish your websites online.

Integrating OpenAuth/OpenID With Your ASP.NET MVC Application