Integrate OpenAuth/OpenID with your existing ASP.NET MVC4 application

In this blog I am going to talk about how to integrate OpenAuth/OpenId with your existing mvc4 application in Visual studio 2012

Step 1: Create a new project

Go to File –> New Project –> Web –> Empty Asp.Net MVC 4 Application

Step 2: Add the following libraries

  • Use Nuget to get the following packages
    • DotNetOpenAuth.AspNet
      • This package is the core package for OAuth/OpenID protocol communication
    • Microsoft.AspNet.Providers.Core
      • This package brings in Universal Providers
    • Microsoft.AspNet.Providers.LocalDb
      • This package sets the connectionstring for the Universal Providers
    • Microsoft.AspNet.Membership.OpenAuth
      • This package provides the extension to integrate OAuth/OpenID with Membership providers

Step 3: Change web.config to use formsauthentication

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

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

Step 5: Adding Login functionality

Add a new controller for Authentication functionality called it AuthController.cs
add Logon Action for login page

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

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

as you can notice its a void action. we are using OAuthWebSecurity.RequestAuthentication this function is requesting the authentication from the requested provider service “Facebook – Twitter – etc.” then it returned to The URL to return to when authentication is successful. we are mentioned “ExternalLoginCallback” as a returned back action

First: 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


Finally: your application is ready to give it a test

You can download a sample from here