Introduction - Google Classroom
Wikipedia says, Google Classroom is a free web service, developed by Google for schools, that aims to simplify creating, distributing, and grading assignments in a paperless way. The primary purpose of Google Classroom is to streamline the process of sharing files between teachers and students. There are many more features of the Google classroom -- click
here to learn more.
In this article, we are going to learn how to integrate the Google classroom with our school information system application. For demo purposes let's consider my sample ASP.NET Core 3.0 as an SIS application, and we will integrate Google classroom with this sample application by pulling out the Google classroom information using Google classroom API’s.
Create a Google Classroom Project
Step 1
Step 2
Create a new project and name it as GoogleClassRoom
Step 3
Enable API by clicking on Enable APIS and Services
Step 4
Now, let’s create a credential (OAuth client ID), where we can get a Client ID and App key which is used to enable the Google authentication in a third party application.
Step 5
In this screen, it will ask you to configure the OAuth consent screen, since we are in the development phase it’s enough to provide the application name and scope details which we are using for our project, as shown below:
classroom.course.readonly is the scope which is used fetch the Google classroom details, add the scope and click on save to save the changes, it will take you to Create OAuth client ID Screen.
Step 6
In Create OAuth client ID screen provide application type as a web application, name the application, in my case I named it as GC client. I will provide authorized Javascript Origins after creating our application. Now click on create, it will generate a Client ID and Client Secret, which should be used in our application for authentication.
Integrate Google Classroom
Step 1
Open Visual Studio -> Create New Project -> Select ASP.NET Core Web Application template, as shown in the below figure.
Step 2
Give a name for a project. In my case, I named it as GoogleClassRoomDemo, Click on next and select Web Application template, as shown in the below figure.
- public IActionResult Index() {
- return View();
- }
View->GoogleClassRoom->Index.cshtml
- <script src="https://code.jquery.com/jquery-3.4.1.min.js"
- integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
- crossorigin="anonymous"></script>
- <script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
- <button id="btnSignIn" class="btn-default" onclick="GoogleAuthenticationPage()">Sign in</button>
- <button class="btn-default" id="googleAuth">Get Course</button>
- <script type="text/javascript">
- function start() {
- gapi.load('auth2', function () {
- auth2 = gapi.auth2.init({
- client_id: "[Provide your client id]",
- scope: 'https://www.googleapis.com/auth/classroom.courses.readonly',
- });
- });
- }
- function GoogleAuthenticationPage() {
- auth2.grantOfflineAccess().then(signInCallback);
- }
- function IsSignedIn() {
- $.ajax({
- url: "/GoogleClassRoom/IsSignedIn", success: function (result) {
- if (result) {
- $("#btnSignIn").hide();
- }
- else {
- $("#googleAuth").hide();
- }
- }
- })
- }
- function signInCallback(authResult) {
- var token = authResult['code'];
- var access_token = '';
- var refresh_token = '';
- $.ajax({
- url: 'https://www.googleapis.com/oauth2/v4/token',
- type: "post",
- datatype: "json",
- contentType: "application/x-www-form-urlencoded; charset=utf-8",
- async: true,
- data: {
- code: authResult['code'], client_id: "[provide client ID ]", client_secret: "[Provide client secret]", redirect_uri: 'https://localhost:44357', grant_type: 'authorization_code'
- },
- success: function (response) {
- access_token = response.access_token;
- refresh_token = response.refresh_token;
- googleCallback(token, access_token, refresh_token);
- }
- })
- .fail(function (err) {
- alert("error" + err);
- console.log("error" + err);
- });
- }
- function googleCallback(authCode, accessToken, refreshToken) {
- if (authCode) {
- $.ajax({
- url: '/GoogleClassRoom/GoogleAuthorizationCallback',
- type: "POST",
- contentType: 'application/json',
- data: JSON.stringify({ Auth_Code: authCode, Access_token: accessToken, Refresh_token: refreshToken }),
- success: function (res) {
- location.reload();
- },
- error: function (xhr) {
- alert("Error" + xhr.responseText);
- }
- });
- } else {
- alert('error');
- }
- }
- </script>
client:platform.js is the Google Client API js, when loading this JS we are calling Start() to initiate auth2 object.
When user clicks on SignIn button it calls GoogleAuthenticationPage(), where we are doing ajax call to trigger 'https://www.googleapis.com/oauth2/v4/token’ google API with clientId and Client secret as one of the parameters in a payload. After successful login from user it will return access token, and refresh token as a response. We are saving these values in the database with a googleCallback() callback.
GoogleClassRoomController.cs
- [HttpPost]
- public void GoogleAuthorizationCallback([FromBody]Token token)
- {
- SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-585QGBN;Initial Catalog=Test;Integrated Security=True");
- SqlCommand cmd = new SqlCommand("Stp_InsertGoogleAccessDetails", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@nvAuthCode", token.Auth_code);
- cmd.Parameters.AddWithValue("@nvRefreshToken", token.Refresh_token);
- cmd.Parameters.AddWithValue("@nvAccessCode", token.Access_token);
- cmd.Parameters.AddWithValue("@inUserID", 1);
- con.Open();
- cmd.ExecuteNonQuery();
- con.Close();
- }
GoogleAuthorizationCallback() method is used to save the Auth code, refresh token and access token and current user id which is maintained in our session into our database, now for time being I hardcoded the value for UserId, basically this unmanaged ADO.NET code should be in a separate data access layer. Make sure you are taking care of it.
SQL script Table
- CREATE TABLE [dbo].[GoogleUserInfo](
- [UserID] [int] NOT NULL,
- [AuthCode] [nvarchar](max) NULL,
- [ReferehToken] [nvarchar](max) NULL,
- [AccessCode] [nvarchar](max) NULL,
- CONSTRAINT [pk_user_id] PRIMARY KEY CLUSTERED
- (
- [UserID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Stored Procedure to insert a record
- CREATE procedure [dbo].[Stp_InsertGoogleAccessDetails]
- (
- @nvAuthCode nvarchar(max) ,
- @nvRefreshToken nvarchar(max),
- @nvAccessCode nvarchar(max),
- @inUserID int
- )
- as
- begin
- insert into GoogleUserInfo values(@inUserID,@nvAuthCode,@nvRefreshToken,@nvAccessCode)
- end
Stored Procedure to get a refresh token
- Create procedure [dbo].[Stp_GetGoogleUserInfo]
- ( @inUserID int
- )
- as
- begin
- select ReferehToken from GoogleUserInfo where UserID=@inUserID
- end
Once user has successfully logged with Google, now he/she can retrieve their Google classroom list,
Clicking on Get Course button will call the function which is returned below,
- $("#googleAuth").click(function (e) {
- $.ajax({
- url: "/GoogleClassRoom/GetCourse", success: function (result) {
- }
- })
- })
This click event will do the ajax call "/GoogleClassRoom/GetCourse"
GoogleClassRoomController.cs
- public class GoogleClassRoomController: Controller {
- private static readonly string ClientId =
- "[Provide client ID]";
- private static readonly string ClientSecret =
- "[Provide client secret]";
- private static readonly string GoogleApplicationName =
- "GoogleClass";
- public IActionResult Index() {
- return View();
- }
- public bool IsSignedIn() {
- string refreshToken = GetRefershToken(1);
- if (string.IsNullOrEmpty(refreshToken)) {
- return true;
- } else {
- return false;
- }
- }
- public List < Course > GetCourse() {
- var Token = GetAuthenticator();
- var token = new TokenResponse() {
- AccessToken = Token,
- ExpiresInSeconds = 3600,
- IssuedUtc = DateTime.UtcNow
- };
- var authflow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer {
- ClientSecrets = new ClientSecrets {
- ClientId = ClientId,
- ClientSecret = ClientSecret
- }
- });
- var credential = new UserCredential(authflow, "0", token);
- var serviceInitializer = new BaseClientService.Initializer() {
- ApplicationName = GoogleApplicationName,
- HttpClientInitializer = credential
- };
- var googleService = new ClassroomService(serviceInitializer);
-
- string pageToken = null;
- var courses = new List < Course > ();
- do {
- var request = googleService.Courses.List();
- request.PageSize = 100;
- request.PageToken = pageToken;
- var response = request.Execute();
- courses.AddRange(response.Courses);
- pageToken = response.NextPageToken;
- } while (pageToken != null);
- return courses;
- }
- public static string GetAuthenticator() {
- string refreshToken = GetRefershToken(1);
- var content = "refresh_token=" + refreshToken + "&client_id=" + ClientId + "&client_secret=" + ClientSecret + "&grant_type=refresh_token";
- var request = WebRequest.Create("https://accounts.google.com/o/oauth2/token");
- request.Method = "POST";
- byte[] byteArray = Encoding.UTF8.GetBytes(content);
- request.ContentType = "application/x-www-form-urlencoded";
- request.ContentLength = byteArray.Length;
- using(var dataStream = request.GetRequestStream()) {
- dataStream.Write(byteArray, 0, byteArray.Length);
- dataStream.Close();
- }
- var response = (HttpWebResponse) request.GetResponse();
- var responseDataStream = response.GetResponseStream();
- var reader = new StreamReader(responseDataStream);
- var responseData = reader.ReadToEnd();
- reader.Close();
- responseDataStream.Close();
- string accessToken;
- if (response.StatusCode == HttpStatusCode.OK) {
- var returnedToken = JsonConvert.DeserializeObject < Token > (responseData);
- accessToken = returnedToken.Access_token;
- } else {
- return string.Empty;
- }
- response.Close();
- return accessToken;
- }
- [HttpPost]
- public void GoogleAuthorizationCallback([FromBody] Token token) {
- SqlConnection con = new SqlConnection(@ "Data Source=DESKTOP-585QGBN;Initial Catalog=Test;Integrated Security=True");
- SqlCommand cmd = new SqlCommand("Stp_InsertGoogleAccessDetails", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@nvAuthCode", token.Auth_code);
- cmd.Parameters.AddWithValue("@nvRefreshToken", token.Refresh_token);
- cmd.Parameters.AddWithValue("@nvAccessCode", token.Access_token);
- cmd.Parameters.AddWithValue("@inUserID", 1);
- con.Open();
- cmd.ExecuteNonQuery();
- con.Close();
- }
- public static string GetRefershToken(int userId) {
- string refreshToken = string.Empty;
- SqlConnection con = new SqlConnection(@ "Data Source=DESKTOP-585QGBN;Initial Catalog=Test;Integrated Security=True");
- SqlCommand sqlCommand = new SqlCommand("Stp_GetGoogleUserInfo", con) {
- CommandType = CommandType.StoredProcedure
- };
- SqlCommand cmd = sqlCommand;
- cmd.Parameters.AddWithValue("@inUserID", userId);
- con.Open();
- SqlDataReader rdr = cmd.ExecuteReader();
- while (rdr.Read()) {
- refreshToken = rdr["ReferehToken"].ToString();
- }
- return refreshToken;
- }
- }
Install Google Classroom API’s package from Nuget package manager
When GetCourse Method is called, it will use GetAutheticator function to get the new accessToken for the current user based on the Refresh token which is saved in our database.
GetRefreshToken() is used to return the refresh token for the current user.
GoogleAuthorizationCodeFlow is used to construct the Google auth flow by initializing the client secrets
UserCredential is used to construct the new credential instance with authflow and token
The ClassroomService class is used to retrieve all Google classroom services based on the service initializer which holds the credentials.
https://accounts.google.com/o/oauth2/token this Google API is used to get the new access token based on a refresh token.
Before testing the application, login into the Google developer console and register our localhost (https://localhost:44357) which is used for development against the OAuth credential which we created.
Now run the application,
Click on Sign in button, it will take you to the Google authentication page, after successful login, the user tokens are saved in our database.
Now, click on Get Course button to get the Google classroom list.
The above figure shows the response from GetCourse().
The list of classrooms that are available in my Google classroom, as shown in the below figure.
Reference
https://developers.google.com/classroom/quickstart/dotnet
Summary
We have gone through,
- Creating the project in Google developer console and enabling the google classroom API.
- Creating the OAuth Credential for the authentication which is used for integration with our application using the developer console.
- Integrating Google API’s in our web application.
- Retrieving the Google classroom course using the google classroom API’s from our ASP.NET Core web application.
Click
here for the source code.