Implement social authentications in Asp.Net MVC with database

Updated : Nov 07, 2019 in Articles

How to Implement social authentications in Asp.Net MVC with database

In this article we will learn How to Implement social authentications in Asp.Net MVC with database

In this Example we will implement step by step how to integrate social logins(like Google,Facebook,twitter) in your Asp.Net MVC Application

Different type of Social Logins

  1. Google
  2. FaceBook
  3. twitter
Implement social authentications in Asp.Net MVC with database
Implement social authentications in Asp.Net MVC with database

before going to implementing social authentications first we will create table on database name like userprofile execute given blow sql query in your database

CREATE TABLE [dbo].[Userprofile](
	[Pk_UserId] [int] IDENTITY(1,1) NOT NULL,
	[UserName] [nvarchar](50) NULL,
	[Pasword] [nvarchar](50) NULL,
	[EmailId] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedDate] [datetime] NULL,
	[DeletedFlag] [nvarchar](50) NULL,
	[updatedUser] [int] NULL,
	)

Add your connection string in your web.config file

 <connectionStrings>
    <add name="TurorialHeperDB" connectionString="Data Source=yourSQLinstancename;Initial Catalog=yourdatabasename;User ID=sa;Password=yourpassword" />
  </connectionStrings>

1. Implementing google authentication login in Asp.net Mvc

if you want to implement google authentication in Asp.net Mvc you need to required GoogleClientIDKey and GoogleClientsecretKey

follow the google developer console link and setup your client id,key Google Developer Console

google authentication login in Asp.net Mvc
google authentication login in Asp.net Mvc

if you are using your local host enter localhost or else enter your domain name

Go to your web.config file Add keys under configuration appSettings see geven code

 <appSettings>
   
    <add key="ClientId" value="you key" />
    
    <add key="FBclient_id" value="you key" />
    <add key="FBclient_secret" value="you key" />

    <add key="Twitterclient_id" value="you key" />
    <add key="Twitterclient_id" value="you key" />

  </appSettings>

Go to your controller folder Add controller name like account controller and create a signUp action method for implementing social logins in mvc

 [HttpGet]
        public ActionResult SignUp()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

Create a model class for saving Google data in your database

public class UserProfile
    {
        public int Pk_UserId { get; set; }
        [Required]
        public string UserName { get; set; }
        [Required]
        public string EmailId { get; set; }
        [Required]
        public string Pasword { get; set; }
        public DateTime CreatedDate { get; set; }
        public DateTime UpdatedDate { get; set; }
        public string DeletedFlag { get; set; }
        public int updatedUser { get; set; }
    }

create view for signUp action method and read GoogleClientId through configurationmanager

@model TutorialHelperFourm.DBModels.UserProfile
@using System.Configuration;

@{
    ViewBag.Title = "RegistrationuserProfile";
    string _googlesitekey = ConfigurationManager.AppSettings["ClientIdGoogleSitekey"];
}

<br />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<div class="login" style="border: 1px solid #ccc;">
    <h2>Join Today</h2>
    <div class="lock"> <img src="images/lock.png" alt="" title=""> </div>
    <p>Choose on of the following up methods</p>
    <div class="button">
        <a class="tw" href="#"> <span class="anc-tw"> </span> Twitter</a>
        <a class="fa" href="/Account/Facebook"> <span class="anc-fa"> </span> Facebook</a>
        <a class="go" href="#" id="googleplus" onclick="login();"><span class="anc-go"> </span>Google+</a>
    </div>
    <span class="line"> </span>
    <p>Or signup using Your Email address</p>
    @using (Html.BeginForm("SignUp", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
    {
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.ValidationMessage("UserName", "", new { @class = "text-danger" })
        <input type="text" id="UserName" name="UserName" class="user active " placeholder="Enter your full name..." onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email address:';}">
        <br />

        @Html.ValidationMessage("EmailId", "", new { @class = "text-danger" })

        <input type="text" id="EmailId" name="EmailId" class="email " placeholder="Enter your email address..." onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email address:';}">
        <br />

        @Html.ValidationMessage("Pasword", "", new { @class = "text-danger" })
        <input type="password" id="Pasword" name="Pasword" class="Pasword" placeholder="Password..." onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email address:';}">
        <br />

        <input type="submit" class="acc btn btn-info" value="Signup My Account " />
        <br />
        <div class="Alredy_signup">
            <label>Alredy you have SignUp</label>
            <a class="accc" href="Login">Login<span class="arrows"> </span></a>
        </div>
    }
</div>
<script type="text/javascript">
    var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
    var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
    var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
    var CLIENTID = '@_googlesitekey';
    var REDIRECT = 'http://localhost:55932';
    var LOGOUT = 'http://localhost:55932';
    var TYPE = 'token';
    var _url = OAUTHURL + 'scope=' + SCOPE + '&amp;client_id=' + CLIENTID + '&amp;redirect_uri=' + REDIRECT + '&amp;response_type=' + TYPE;
    var acToken;
    var tokenType;
    var expiresIn;
    var user;
    var loggedIn = false;
    function login() {
        var win = window.open(_url, "windowname1", 'width=800, height=600');
        var pollTimer = window.setInterval(function () {
            try {
                console.log(win.document.URL);
                if (win.document.URL.indexOf(REDIRECT) != -1) {
                    window.clearInterval(pollTimer);
                    var url = win.document.URL;
                    acToken = gup(url, 'access_token');
                    tokenType = gup(url, 'token_type');
                    expiresIn = gup(url, 'expires_in');

                    win.close();
                    validateToken(acToken);
                }
            }
            catch (e) {

            }
        }, 500);
    }
    function gup(url, name) {
        namename = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\#&amp;]" + name + "=([^&amp;#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(url);
        if (results == null)
            return "";
        else
            return results[1];
    }
    function validateToken(token) {
        getUserInfo();
        $.ajax(
            {
                url: VALIDURL + token,
                data: null,
                success: function (responseText) {
                },
            });
    }

    function getUserInfo() {
        $.ajax({
            url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
            data: null,
            success: function (resp) {
                $.ajax({
                    url: '/Account/GoogleLogin/',
                    type: 'POST',
                    data: {
                        email: resp.email,
                        name: resp.name,
                    },
                    success: function () {
                        window.location.href = "/Home/Index/";
                    },
                });
            },
        });
    }
</script>

After googleautentication successful we will save data in our database for that we will implement action method name like GoogleLogin

[HttpPost]
        public void GoogleLogin(string email, string name)
        {
            string queryvalues = string.Format("'{0}',", name);
            queryvalues += string.Format("'{0}',", email);
            queryvalues += string.Format("'{0}',", "");
            queryvalues += string.Format("'{0}',", DateTime.Now);
            queryvalues += string.Format("'{0}'", "N");
            string query = "UserName,EmailId,Pasword,CreatedDate,DeletedFlag";

            string wherecondition = string.Format("EmailId ='{0}'", email);
            int val = objhelper.CheckdataExists(wherecondition, "EmailId", "Userprofile");
            if (val == 0)
            {
                objhelper.InsertData("Userprofile", query, queryvalues);
            }
            else
            {
                string updateQuery = string.Format("UserName='{0}',", name);
                updateQuery += string.Format("EmailId='{0}',", email);
                updateQuery += string.Format("Pasword='{0}',", "");
                updateQuery += string.Format("CreatedDate='{0}',", DateTime.Now);
                updateQuery += string.Format("DeletedFlag='{0}'", "N");

                objhelper.UpdateData("Userprofile", updateQuery, wherecondition);
            }
            TempData["email"] = email;
            TempData["first_name"] = name;
            FormsAuthentication.SetAuthCookie(email, false);
        }

For saving data in your database we will implement Ado.Net helper methods InsertData for first time signup,UpdateData helper method for up date next time user is signup

 public int InsertData(string tableName, string paramList, string paramValues)
        {
            int result = -1;
            try
            {
                string query = "INSERT INTO " + tableName + "(" + paramList + ") VALUES(" + paramValues + ") SELECT IDENT_CURRENT('" + tableName + "')";
                using (SqlConnection conn = new SqlConnection(sqlConnectionString))
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand(query, conn);
                    result = Convert.ToInt32(cmd.ExecuteScalar());
                    //result = 1;
                }
            }
            catch (Exception ex)
            {
                result = 0;
            }
            return result;
        }
public int UpdateData(string tableName, string paramDetails, string whereCondition)
        {
            string query = String.Empty;
            int result = -1;
            try
            {
                if (!String.IsNullOrEmpty(whereCondition))
                {
                    query = "UPDATE " + tableName + " SET " + paramDetails + " WHERE " + whereCondition;
                }
                else
                {
                    query = "UPDATE " + tableName + " SET " + paramDetails;
                }
                using (SqlConnection conn = new SqlConnection(sqlConnectionString))
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand(query, conn);
                    result = cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                result = 0;
            }
            return result;
        }

2. Implementing FaceBook authentication login in Asp.net Mvc

if you want to implement FaceBook authentication in Asp.net MVC we will need FBclient_id and FBclient_secret

follow the FaceBook developer console link and setup your client id,key FaceBook Developer Console

FaceBook authentication login in Asp.net Mvc
FaceBook authentication login in Asp.net Mvc

the above facebook App Id, App Secret keys you will enter in web.config File

Go to you account controller implement Facebook,FacebookCallback,RediredtUri action methods

After successfully authenticated through facebook we will save data in our data base for that we will implement the code in FacebookCallback Action method

 private Uri RediredtUri
        {
            get
            {
                var uriBuilder = new UriBuilder(Request.Url);
                uriBuilder.Query = null;
                uriBuilder.Fragment = null;
                uriBuilder.Path = Url.Action("FacebookCallback");
                return uriBuilder.Uri;
            }
        }

        [AllowAnonymous]
        public ActionResult Facebook()
        {
            var fb = new FacebookClient();
            var loginUrl = fb.GetLoginUrl(new
            {
                client_id = ConfigurationManager.AppSettings["FBclient_id"],
                client_secret = ConfigurationManager.AppSettings["FBclient_secret"],
                redirect_uri = RediredtUri.AbsoluteUri,
                response_type = "code",
                scope = "email"
            });
            return Redirect(loginUrl.AbsoluteUri);
        }

        public ActionResult FacebookCallback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = ConfigurationManager.AppSettings["FBclient_id"],
                client_secret = ConfigurationManager.AppSettings["FBclient_secret"],
                redirect_uri = RediredtUri.AbsoluteUri,
                code = code
            });
            var accessToken = result.access_token;
            Session["AccessToken"] = accessToken;
            fb.AccessToken = accessToken;
            dynamic me = fb.Get("me?fields=link,first_name,currency,last_name,email,gender,locale,timezone,verified,picture,age_range");
            string email = me.email;
            TempData["email"] = me.email;
            TempData["first_name"] = me.first_name;
            TempData["lastname"] = me.last_name;
            TempData["picture"] = me.picture.data.url;
            FormsAuthentication.SetAuthCookie(email, false);

            string queryvalues = string.Format("'{0}',", me.first_name + me.last_name);
            queryvalues += string.Format("'{0}',", me.email);
            queryvalues += string.Format("'{0}',", "");
            queryvalues += string.Format("'{0}',", DateTime.Now);
            queryvalues += string.Format("'{0}'", "N");
            string query = "UserName,EmailId,Pasword,CreatedDate,DeletedFlag";

            string wherecondition = string.Format("EmailId ='{0}'", me.email);
            int val = objhelper.CheckdataExists(wherecondition, "EmailId", "Userprofile");
            if (val == 0)
            {
                objhelper.InsertData("Userprofile", query, queryvalues);
            }
            else
            {
                string updateQuery = string.Format("UserName='{0}',", me.first_name + me.last_name);
                updateQuery += string.Format("EmailId='{0}',", me.email);
                updateQuery += string.Format("Pasword='{0}',", "");
                updateQuery += string.Format("CreatedDate='{0}',", DateTime.Now);
                updateQuery += string.Format("DeletedFlag='{0}'", "N");

                objhelper.UpdateData("Userprofile", updateQuery, wherecondition);
            }
            return RedirectToAction("Index", "Home");
        }

for insert and update we will use same above Ado.net helper method

3. Implementing Twitter authentication login in Asp.net Mvc

for Implementing Twitter authentication login also we want same clientid,key like as google,fb go to twitter developer console setup your id,key

Twitter authentication login in Asp.net Mvc
Twitter authentication login in Asp.net Mvc

enter above Access Token,Access Token Secret keys in web.config file this keys you will read at controller level through configurationmanager

 [HttpGet]
        public ActionResult TwitterAuth()
        {
            string Key = ConfigurationManager.AppSettings["Twitterclient_id"];
            string Secret = ConfigurationManager.AppSettings["Twitterclient_id"];
            TwitterService service = new TwitterService(Key, Secret);
            OAuthRequestToken requestToken = service.GetRequestToken("http://localhost:33916/Home/TwitterCallback");
            Uri uri = service.GetAuthenticationUrl(requestToken);
            return Redirect(uri.ToString());
        }

        public ActionResult TwitterCallback(string oauth_token, string oauth_verifier)
        {
            var requestToken = new OAuthRequestToken { Token = oauth_token };
            string Key = ConfigurationManager.AppSettings["Twitterclient_id"];
            string Secret = ConfigurationManager.AppSettings["Twitterclient_id"];

            try
            {
                TwitterService service = new TwitterService(Key, Secret);
                OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier);
                service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
                VerifyCredentialsOptions option = new VerifyCredentialsOptions();

                TwitterUser user = service.VerifyCredentials(option);
                TempData["Name"] = user.Name;
                TempData["Userpic"] = user.ProfileImageUrl;
                return View();
            }
            catch
            {
                throw;
            }
        }

Summary

In this article we will learned about how to Implement social authentications in Asp.Net MVC with database next article we will learn LinkedIn,fiverr authentications