In this article I will explain with an example, how to login with Google in ASP.Net MVC.
In this article, ASPSnippets.GoogleAPI Library will be used for login with Google in ASP.Net MVC.
Download ASPSnippets.GoogleAPI Library
You can download the latest ASPSnippets.GoogleAPI.dll from the following link.
Note: You will need add the reference of ASPSnippets.GoogleAPI DLL in your project.
Getting Google API Client ID and Client Secret
In order to use Google Account API for login, you will need to create an Application in Google Console and get Client ID and Client Secret. For details please refer the following article.
Model
The Model class consists of following properties.
public class GoogleProfileModel
{
public string Id { get; set; }
public string Name { get; set; }
public string Picture { get; set; }
public string Email { get; set; }
public string Verified_Email { get; set; }
public bool IsLoggedIn { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.Web.Script.Serialization;
using ASPSnippets.GoogleAPI;
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this action method, first the ClientId, ClientSecret and the RedirectUri properties are set and the GoogleProfileModel instance is created.
Then, a check is performed to access code (access token) in Query string and then using this access code, the user’s Google profile details such as Google Profile ID, Name, Picture, Email and Verified Email Address are fetched as JSON string from Google.
Then, the JSON string is deserialized to the GoogleProfileModel class object and returned to the View.
Note: The returned JSON string consists of some additional information which is not covered in this article, you can easily extend your class to fetch the additional information.
Action method for handling POST operation
Inside this Action method, the value of the clicked Submit button is fetched using its Name from the Request.Form collection and appropriate Action method is called.
Action method for handling Login POST operation
This action method gets called when Login button is clicked.
Inside this Action method, user is redirected to the Google Authorization page using GoogleConnect class, where user has to provide permission to the Application to access Google account details such as Google Profile ID, Name, Picture, Email and Verified Email Address.
Then, request is sent to get access to the Profile and Email details of the user by passing the profile and email scopes to Authorize method respectively and finally, sent back to the URL set as the RedirectUri while creating the application in Google Developer Console.
Action method for handling Clear POST operation
This action method gets called when Clear button is clicked.
Inside this action method, the GoogleConnect class clears the current access token. Thus when some user logs out of the website, this method can be used to clear his current session.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
GoogleConnect.ClientId = "<Google Client ID>";
GoogleConnect.ClientSecret = "<Google Client Secret>";
GoogleConnect.RedirectUri = Request.Url.AbsoluteUri.Split('?')[0];
GoogleProfileModel profile = new GoogleProfileModel();
if (!string.IsNullOrEmpty(Request.QueryString["code"]))
{
string code = Request.QueryString["code"];
string json = GoogleConnect.Fetch("me", code);
profile = new JavaScriptSerializer().Deserialize<GoogleProfileModel>(json);
profile.IsLoggedIn = true;
}
if (Request.QueryString["error"] == "access_denied")
{
ViewBag.Message = "Access denied.";
}
return View(profile);
}
[HttpPost]
public ActionResult Index(string submit)
{
switch (submit)
{
case "Login":
return Login();
case "Clear":
return Clear();
}
return View();
}
[HttpPost]
public ActionResult Login()
{
GoogleConnect.Authorize("profile", "email");
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Clear()
{
GoogleConnect.Clear(Request.QueryString["code"]);
return RedirectToAction("Index");
}
}
View
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The following Form consists of a Button to allow user login with Google Account API, an Image and some SPAN controls to display the user’s Google Profile details.
There is also, another Button which will be used to logs out of the website.
When the Buttons are clicked, the form is submitted to the Controllers Action Method.
Finally, the ViewBag object is checked for NULL and if it is not NULL then the value of the ViewBag object is displayed using JavaScript Alert Message Box.
@model Google_SignIn_MVC.Models.GoogleProfileModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<input type="submit" value="Login" name="Submit" @(Model.IsLoggedIn ? "disabled" : "")/>
if (Model.IsLoggedIn)
{
<hr/>
<table>
<tr>
<td rowspan="6" valign="top">
<img src="@Model.Picture" Width="50" Height="50" />
</td>
</tr>
<tr>
<td>ID: <span>@Model.Id</span></td>
</tr>
<tr>
<td>Name: <span>@Model.Name</span></td>
</tr>
<tr>
<td>Email: <span>@Model.Email</span></td>
</tr>
<tr>
<td>Verified Email: <span>@Model.Verified_Email</span></td>
</tr>
<tr>
<td><input type="submit" value="Clear" name="Submit" /></td>
</tr>
</table>
}
}
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert('@ViewBag.Message');
};
</script>
}
</body>
</html>
Errors
Following are some errors that you might encounter when using the ASPSnippets.GoogleAPI in your projects.
1. invalid_client
The cause of this error is directly related to the Client ID and Client Secret and hence you need to make sure that you have supplied a valid Client ID and Client Secret.
2. invalid_request
This error will occur when the Client ID and/or Client Secret is blank or not supplied.
3. redirect_uri_mismatch
This error will occur when the RedirectUri set in the code is not matching with the RedirectUri set while configuring the application in Google Developer Console.
Screenshot
Demo
Downloads