Enable Javascript

Please enable Javascript to view website properly

Toll Free 1800 889 7020

Looking for an Expert Development Team? Take two weeks Trial! Try Now

Learn how asp.net developers do social media authentication in MVC development

Asp.net development is an interesting platform and major developers today, are learning and grasping skills to make best development practices. This article is about asp.net developers' techniques to authenticate social media in MVC. You will learn every step involved in the process of authentication of FB/Google+ in MVC development.

In this section we covered following points,

Why social media authentication is important to add in your web site?

One of the core functions of any modern website is the ability to leverage Social Authentication (also known as Social Login).

Normally in any website, we develop there are two common features is there login and registration. In registration, we ask for basic information to fill from the user. And at the back, we store user-filled information in the database and give users unique identification through identifying users when it’s login into our website. Now a day’s everything is online and most of the work is done through the web. So as a user point you, he/she might be going through normal procedure to fill form and register and after registration login and access the website.

So, Social login is a form of single sign-on using existing login information from an identity provider such as Facebook, Twitter, Google, or Microsoft to sign into a third-party website and using third party response create a new login account specifically for your website.

Is Login with social media is secure?

Social login is powered by OAuth. OAuth is an open standard for authorization. OAuth provides client applications 'secure delegated Access’ to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. Specifically designed to work with Hypertext Transfer Protocol (HTTP), OAuth essentially allows third-party clients to issue access tokens through authorization servers, with the consent of the resource owner or end-user. The client then uses the access token to access the protected resources hosted by the resource server. OAuth is commonly used as a way for web surfers to log into third-party websites using their Facebook, Twitter, Google, or Microsoft accounts, without worrying about their access credentials being compromised.

Basic work flow of social media authentication

img 1

How to implement login with Facebook and Google+?

1) Login with Facebook.

To implement login with Facebook in Asp.net web form you might follow the below step.

<Script> window.fbAsyncInit = function () { FB.init({ AppId: 'app id', xfbml: true, version: 'v2.5' }); }; (function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); function ShowMyName() { FB.getLoginStatus(function (response) { if (response.status == 'connected') { onLogin(response); } else { FB.login(function (response) { onLogin(response); }, { scope: 'user_friends, email' }); } }); } function onLogin(response) { if (response.status == 'connected') { FB.api('/me?fields=first_name,last_name,name,email,gender,birthday,bio,hometown,education,quotes,cover,work,devices', function (data) { var welcomeBlock = document.getElementById('fb-welcome'); var test = { email: data.email, password: data.first_name, FirstName: data.first_name, LastName: data.last_name, Gender: data.gender, Mobile: "", BirthDate: "", City: "", IsDeleted: false, isSocialMediaUser: true, SocialMedia: 'FB' }; var studentdata = JSON.stringify(test); $.ajax({ url: "/Login/SocialMediaLogin", type: "POST", dataType: "json", data: { studentdata: studentdata, BranchID: branchId, ActionPerform: actionPerform, ImageUrl: imageUrl }, Success: function (FeeListResp, textStatus, jqXHR) { window.location.href = ‘@Url.Action("Index", "Home") '; }, Error: function (jqXHR, textStatus, errorThrown) { }, Complete: function () { } }); }); } } </Script>

And Now Add One Button to invoke request to login with Facebook.

<a onclick="ShowMyName()">Continue with Facebook</a>

Now all is Done, Login with Facebook is successfully integrate with your Website.

2) Login with Google +.

To implement login with Google + in the Asp.net web form you might follow the below step.

<script> function onLoadCallback() { gapi.load('plus', 'v1', function () { }); } function logout() { gapi.auth.signOut(); location.reload(); } function login() { var myParams = { 'clientid': xxxxxxxxx6tpsi2r94q2s42.apps.googleusercontent.com', 'cookiepolicy': 'single_host_origin', 'callback': 'loginCallback', 'approvalprompt': 'force', 'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email' }; gapi.auth.signIn(myParams); } function loginCallback(result) { if (result['status']['signed_in']) { gapi.client.load('plus', 'v1').then(function () { var request = gapi.client.plus.people.get({ 'userId': 'me' }); request.execute(function (request) { var temp = request.image.url.split('?'); var url = temp[0] + '?sz=100'; var test = { email: request.emails[0].value, password: request.name.givenName, FirstName: request.name.givenName, LastName: request.name.familyName, Gender: request.gender, Mobile: "", BirthDate: "", City: "", IsDeleted: false, isSocialMediaUser: true, SocialMedia: 'G+' }; var studentdata = JSON.stringify(test); $.ajax({ url: "/Login/SocialMediaLogin", type: "POST", dataType: "json", data: { studentdata: studentdata, BranchID: branchId, Action Perform: actionPerform, ImageUrl: url }, Success: function (FeeListResp, textStatus, jqXHR) { window.location.href = ‘@Url.Action("Index", "Home") '; }, Error: function (jqXHR, textStatus, errorThrown) { }, Complete: function () { } }); }); }); } } </script>

And Now Add One Button to invoke request to login with Google +.

<p><a on click="login ()">Continue with Google+</a></p>

Now all is Done, Login with Facebook is successfully integrated with your Website. Now at the back end, you have to implement a method that stores the information and authenticates the user when the second time comes.

[HttpPost] public JsonResult SocialMediaLogin(string studentdata) { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); Student objStudent = jsonSerializer.Deserialize<Student> (studentdata); var email = objStudent.Email; string userName = Membership.GetUserNameByEmail(email); if (string.IsNullOrEmpty(userName)) { var user = Membership.CreateUser(email, "letscareerpedia", email); FormsAuthentication.SetAuthCookie(email, false); return Json(new { result = "Redirect", url = Url.Action("Index", "Home") }); } else { MembershipUser oMu = Membership.GetUser(userName); FormsAuthentication.SetAuthCookie(email, false); return Json(new { result = "Redirect", url = Url.Action("Index", "Home") }); }

Sample App with API Response Example

So, in the above screen is the response that came from the Google + API. Here response contains user profile information with email and one unique id to identify the user. The rest of the other process is the same as Facebook so, convert response in JSON Object and invoke particular controller action method to further process the login request. The author has used simple coding and techniques to make you learn the process of authentication of FB/ Google+ in MVC development. This article is purposely intended for asp.net developers and the development community, indeed.

Recent Blogs

Categories

NSS Note

Some of our clients

team