How can authenticate user by their Google, Yahoo or OpenID accounts in MVC?

One of the major problem for websites users is that they have to create account for too many websites which they want to use, and it is hard to remember all accounts information. One the best solution is that users login to your website with another account that already have , same as Google , Microsoft , Facebook, Twitter and etc…

Today I am going to teach you how let users to connect to your website by these three accounts

  1. Google ( Gmail)
  2. Yahoo
  3. OpenId

Let start with making some changes in the AuthConfig.cs file, you can access to this file from the App_Start folder in application root, as you see here the code in the file is commented, we need to change it to this:

Before you change the code, should add these reference to the class,

using DotNetOpenAuth.OpenId.RelyingParty;
using Microsoft.Web.WebPages.OAuth;
using MvcAuction.Models;

And your code should be like this :

public static class AuthConfig
    {
        public static void RegisterAuth()
        {

            OAuthWebSecurity.RegisterGoogleClient();
            OAuthWebSecurity.RegisterYahooClient();

            var MyOpenIdClient =
new OpenIdClient("myopenid", WellKnownProviders.MyOpenId);
            OAuthWebSecurity.RegisterClient(MyOpenIdClient, "myOpenID", null);
        }
    }

You need these three critical functions to authenticate the users:
1. Offers the list of available providers.

public ActionResult Login()
        {

            ViewBag.List = OAuthWebSecurity.RegisteredClientData;

           return View();

        }

Here there is a sample code for View file, that shows you how retrieve data from above function and show them as list of button to users

 <form method="post" action="/AdminUsers/ExternalLogins" > 
        <p> 
    @foreach (AuthenticationClientData p in ViewBag.List)
        {
            <button type="submit" name="provider" value="@p.AuthenticationClient.ProviderName" title="Log in using your @p.DisplayName account">@p.DisplayName</button>
        }
        </p>
</form>

2. When the user click on one of the buttons that you created for each provider, this function will be run and sends request to the provider :

 public void ExternalLogins(string Provider)
         {
             OAuthWebSecurity.RequestAuthentication(Provider,"/home/GetResult");

         }

3. This function gets the result from provider and you can make appropriate decision Based on result:

  public ActionResult GetResult()
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication();
            return View();
        }

As I said before , may the posts on MVC will not be clear or easy for those programmer that are new in MVC, therefore please feel free to contact me if you have any questions or leave comment here, good luck