Here in This Article I am going to explain you how to implement Login with Google in your website. first of all you need to create a new project in Google developers console. https://console.developers.google.com/
Select your existing project. if you haven't created then first of all Create a new Project.
Provide Project Name. I have provided "LoginWithGoogle". click on Create button.
Now Click on Credentials Link on Left Side Menu.
Click On OAuth consent screen Link and Fill the information. finally click on Save button.
It will Redirect you to the Credentials Page.
Click on Create credentials Button. it'll open a menu. Click on OAuth client ID.
Click on Web application Radio button.
Fill the Information and Click on Create Button. It'll generate Client ID and Client Secret Key.
Finally Click On Save Button.
Now You have Client ID and Secret Key for your Login with Google functionality.
Now come to your Visual Studio Project.
Create a new MVC Project.
In the Model Folder Create a new Model class.
public class GoogleDataModel
{
public string Email_address { get; set; }
public string Google_ID { get; set; }
public string firstName { get; set; }
public string LastName { get; set; }
public string fullName { get; set; }
public string Client_ID { get; set; }
public string Return_url { get; set; }
public string userProfilePic { get; set; }
public string Gender { get; set; }
}
In the Home Controller add the Client Key and Secret Key.
In the Index View Add the Login Button and Some Javascript Code.
Now, In the GetGoogleAccount View Add the Below Code.
Now, In the About Action add the below Code.
Add the Code in About.cshtml
Now you're done. Run the Application.
Provide the Email Id and Password. Click on Sign In Button.
public class HomeController : Controller
{
string clientId = "767676544437878-m5h7tpngqjkch6sr9visngstdu09agic.apps.googleusercontent.com";
string clientSecret = "qL78qLvihhfgf9VWT189898fG9";
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult GetGoogleAccount()
{
return View();
}
------
---------
In the Index View Add the Login Button and Some Javascript Code.
<input type="button" id="Button1" value="Login With Google" onclick="OpenGoogleLoginPopup();" />
<script type="text/javascript" language="javascript">
var clientId = "767676544437878-m5h7tpngqjkch6sr9visngstdu09agic.apps.googleusercontent.com";
function OpenGoogleLoginPopup() {
var url = "https://accounts.google.com/o/oauth2/auth?";
url += "scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&";
url += "state=%2Fprofile&"
url += "redirect_uri=http://localhost:53285/Home/GetGoogleAccount&"
url += "response_type=token&"
url += "client_id="+clientId;
window.location = url;
}
</script>
Now, In the GetGoogleAccount View Add the Below Code.
@{
ViewBag.Title = "GetGoogleAccount";
}
<script type="text/javascript">
try {
debugger;
// First of all, parse the querystring
var params = {}, queryString = location.hash.substring(1),regex = /([^&=]+)=([^&]*)/g, m;
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
var ss = queryString.split("&")
if (ss != undefined) {
window.location = "About?" + ss[1];
history.pushState("", "", "About");
}
else
window.location = "About";
} catch (exp) {
}
</script>
Now, In the About Action add the below Code.
public ActionResult About()
{
GoogleDataModel model = new GoogleDataModel();
if (Request.QueryString["access_token"] != null)
{
string test = Request.QueryString["access_token"];
}
if (Request.QueryString["access_token"] != null)
{
String URI = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + Request.QueryString["access_token"].ToString();
WebClient webClient = new WebClient();
Stream stream = webClient.OpenRead(URI);
string b;
/*I have not used any JSON parser because I do not want to use any extra dll/3rd party dll*/
using (StreamReader br = new StreamReader(stream))
{
b = br.ReadToEnd();
}
b = b.Replace("id", "").Replace("email", "");
b = b.Replace("given_name", "");
b = b.Replace("family_name", "").Replace("link", "").Replace("picture", "");
b = b.Replace("gender", "").Replace("locale", "").Replace(":", "");
b = b.Replace("\"", "").Replace("name", "").Replace("{", "").Replace("}", "");
/*
"id": "109124950535374******"
"email": "usernamil@gmail.com"
"verified_email": true
"name": "firstname lastname"
"given_name": "firstname"
"family_name": "lastname"
"link": "https://plus.google.com/10912495053537********"
"picture": "https://lh3.googleusercontent.com/......./photo.jpg"
"gender": "male"
"locale": "en" }
*/
Array ar = b.Split(",".ToCharArray());
for (int p = 0; p < ar.Length; p++)
{
ar.SetValue(ar.GetValue(p).ToString().Trim(), p);
}
model.Email_address = ar.GetValue(1).ToString();
model.Google_ID = ar.GetValue(0).ToString();
model.firstName = ar.GetValue(4).ToString();
model.LastName = ar.GetValue(5).ToString();
model.fullName = model.firstName + " " + model.LastName;
model.Gender = ar.GetValue(8).ToString();
model.userProfilePic = ar.GetValue(7).ToString();
model.userProfilePic = model.userProfilePic.Replace("https", "https:");
}
return View(model);
}
Add the Code in About.cshtml
@model LoginWithFbDemo.Models.GoogleDataModel
@{
ViewBag.Title = "About";
}
<div id="ClientDetails">
<br ><br >
@Html.TextBoxFor(x=> x.fullName)
@Html.TextBoxFor(x=> x.Email_address)
<img id="imgProfile" src="@Model.userProfilePic" style="width:auto"/><br >
</div>
Now you're done. Run the Application.
Click On Login With Google Button.
It'll ask the Permission. Click on Allow button.
It will redirect you to the About Page. You will see your Name, Email Id and Profile Pic.
0 comments:
Post a Comment