Adding Scope in Google Classroom Integration With ASP.NET Core 3.0 Web Application

Introduction
 
In my last article, we have seen how to integrate the Google Classroom with ASP.NET Core web application, in this article you will learn how to add the different scope in Google classroom while integrating with ASP.NET Core 3.0 web application.
 
This is a continuation of my last article.
 
Add Scope
 
Let’s add Google classroom roster scope to fetch the Roster information using Google classroom API’s.
 
Step 1
 
Go to Views->GoogleClassRoom->Index.cshtml, add the below scope https://www.googleapis.com/auth/classroom.rosters in Google auth call. This scope is used to add a permission to get the Google classroom roster information for selected classrooms. 
  1. function start() {    
  2.     gapi.load('auth2'function() {    
  3.         auth2 = gapi.auth2.init({    
  4.             client_id: "Give your client Id",    
  5.             scope: 'https://www.googleapis.com/auth/classroom.courses.readonly https://www.googleapis.com/auth/classroom.rosters',    
  6.         });    
  7.     });    
  8. } 
Complete code
  1. @{  
  2.     ViewData["Title"] = "Index";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  5.   
  6. <!DOCTYPE html>  
  7. <html>  
  8. <head>  
  9.     <style>  
  10.         html {  
  11.             font-size: 14px;  
  12.             font-family: Arial, Helvetica, sans-serif;  
  13.         }  
  14.     </style>  
  15.     <title></title>  
  16.     <script src="https://kendo.cdn.telerik.com/2019.3.1023/js/jquery.min.js"></script>  
  17.     <script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>  
  18.   
  19. </head>  
  20. <body>  
  21.     <div id="example">  
  22.   
  23.         <button id="btnSignIn" class="btn-default" onclick="GoogleAuthenticationPage()">Sign in</button>  
  24.         <button class="btn-default" id="googleAuth">Get Course</button>  
  25.         <div id="grid"></div>  
  26.         <br/>  
  27.         <button type="button" id="btnSelectRow" value="GetValue" class="k-button">Get Student</button>  
  28.         <br/>  
  29.         <div id="StudentList"></div>  
  30.         <script type="text/javascript">  
  31.             function start() {  
  32.                 gapi.load('auth2'function () {  
  33.                     auth2 = gapi.auth2.init({  
  34.                         client_id: "1070617910386-e614kn8nptnf7kpec2fmksoaa3t610gd.apps.googleusercontent.com",  
  35.                         scope: 'https://www.googleapis.com/auth/classroom.courses.readonly https://www.googleapis.com/auth/classroom.rosters',  
  36.                     });  
  37.                 });  
  38.             }  
  39.             function GoogleAuthenticationPage() {  
  40.                 auth2.grantOfflineAccess().then(signInCallback);  
  41.             }  
  42.             function IsSignedIn() {  
  43.   
  44.                 $.ajax({  
  45.                     url: "/GoogleClassRoom/IsSignedIn", success: function (result) {  
  46.                         if (result) {  
  47.                             $("#btnSignIn").hide();  
  48.                         }  
  49.                         else {  
  50.                             $("#googleAuth").hide();  
  51.                         }  
  52.                     }  
  53.                 })  
  54.             }  
  55.             function signInCallback(authResult) {  
  56.                 var token = authResult['code'];  
  57.                 var access_token = '';  
  58.                 var refresh_token = '';  
  59.                 $.ajax({  
  60.                     url: 'https://www.googleapis.com/oauth2/v4/token',  
  61.                     type: "post",  
  62.                     datatype: "json",  
  63.                     contentType: "application/x-www-form-urlencoded; charset=utf-8",  
  64.                     async: true,  
  65.                     data: {  
  66.   
  67.                         code: authResult['code'], client_id: "give your client Id Key", client_secret: "give your client secrete key", redirect_uri: 'https://localhost:44357', grant_type: 'authorization_code'  
  68.                     },  
  69.                     success: function (response) {  
  70.                         debugger;  
  71.                         access_token = response.access_token;  
  72.                         refresh_token = response.refresh_token;  
  73.                         googleCallback(token, access_token, refresh_token);  
  74.                     }  
  75.                 })  
  76.                     .fail(function (err) {  
  77.                         alert("error" + err);  
  78.                         console.log("error" + err);  
  79.                     });  
  80.             }  
  81.   
  82.             function googleCallback(authCode, accessToken, refreshToken) {  
  83.                 if (authCode) {  
  84.                     $.ajax({  
  85.                         url: '/GoogleClassRoom/GoogleAuthorizationCallback',  
  86.                         type: "POST",  
  87.                         contentType: 'application/json',  
  88.                         data: JSON.stringify({ Auth_Code: authCode, Access_token: accessToken, Refresh_token: refreshToken }),  
  89.                         success: function (res) {  
  90.                             location.reload();  
  91.                         },  
  92.                         error: function (xhr) {  
  93.                             alert("Error" + xhr.responseText);  
  94.                         }  
  95.                     });  
  96.                 } else {  
  97.                     alert('error');  
  98.                 }  
  99.             }  
  100.             $("#googleAuth").click(function (e) {  
  101.                 $("#grid").kendoGrid({  
  102.                     dataSource: {  
  103.                         type: "json",  
  104.                         transport: {  
  105.                             read: "/GoogleClassRoom/GetCourse"  
  106.                         },  
  107.                         pageSize: 20  
  108.                     },  
  109.                     selectable: "true",  
  110.                     height: 550,  
  111.                     toolbar: ["search"],  
  112.                     columns: [{  
  113.                         field: "name",  
  114.                         title: "Name"  
  115.                     },]  
  116.                 });  
  117.             })  
  118.             $("#btnSelectRow").click(function () {  
  119.                   
  120.                 var grid = $("#grid").data("kendoGrid");  
  121.                 var selectedItem = grid.dataItem(grid.select());  
  122.                  
  123.                    $("#StudentList").kendoGrid({  
  124.                     dataSource: {  
  125.                         type: "json",  
  126.                         transport: {  
  127.                             read: "/GoogleClassRoom/GetStudents?courseId="+ selectedItem.id  
  128.                         },  
  129.                         pageSize: 20  
  130.                     },  
  131.                     selectable: "true",  
  132.                     height: 550,                      
  133.                     columns: [{  
  134.                         field: "profile.name.fullName" 
  135.                         title: "Name"  
  136.                     },]  
  137.                 });  
  138.             })  
  139.         </script>  
  140.     </div>  
  141. </body>  
  142. </html>  
The Get Student button event is used to call the GetStudent function to get the list of students based on the Classroom selection in the grid.
 
Step 2
 
Go to Controller->GoogleClassRoomController.cs, add the below function which is used to get the list of students based on the classroom id passed to the API.
  1. public List < Student > GetStudents(string courseId) {  
  2.  var Token = GetAuthenticator();  
  3.  var token = new TokenResponse() {  
  4.   AccessToken = Token,  
  5.    ExpiresInSeconds = 3600,  
  6.    IssuedUtc = DateTime.UtcNow  
  7.  };  
  8.   
  9.  var authflow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer {  
  10.   ClientSecrets = new ClientSecrets {  
  11.    ClientId = ClientId,  
  12.     ClientSecret = ClientSecret  
  13.   }  
  14.  });  
  15.   
  16.  var credential = new UserCredential(authflow, "0", token);  
  17.  var serviceInitializer = new BaseClientService.Initializer() {  
  18.   ApplicationName = GoogleApplicationName,  
  19.    HttpClientInitializer = credential  
  20.  };  
  21.   
  22.  var googleService = new ClassroomService(serviceInitializer);  
  23.   
  24.  string pageToken = null;  
  25.  var students = new List < Student > ();  
  26.  do {  
  27.   var request = googleService.Courses.Students.List(courseId);  
  28.   request.PageSize = 100;  
  29.   request.PageToken = pageToken;  
  30.   var response = request.Execute();  
  31.   students.AddRange(response.Students);  
  32.   pageToken = response.NextPageToken;  
  33.  } while (pageToken != null);  
  34.  return students;  
  35. }  
I have given a deep explanation about the authentication in my last article, basically the ClassroomSerive class will provide all the information of google classroom based on the scope added, right now we have two scope 'https://www.googleapis.com/auth/classroom.courses.readonly https://www.googleapis.com/auth/classroom.rosters’
 
Scopes
 
  1. https://www.googleapis.com/auth/classroom.courses.readonly – Is used to fetch the classroom details, which is discussed in my last article.
  2. https://www.googleapis.com/auth/classroom.rosters - Is used to fetch the students list of the classroom, based on the classroom id which is give as input to the API.
 
Step 3
 
Run the application, click on Sign in button to authenticate because now we added a new scope, so it’s a must to reauthenticate the user to register the permission to fetch the roster details.
 
 
 
From the above figure you can notice on the reauthenticate Google prompt the user permission to allow the API to fetch the class roster details.
 
Clicking on Get Course will show the Grid with the Google classroom record list, as shown in the below figure.
 
 
 
Google Classroom list
 
 
 
Same List of classes in Google Classroom dashboard
 
 
Step 4 - Select the class from the grid and click on Get Student button to fetch the list of students available in the selected class. 
 
 
 
API Response
 
 
 
 
 
From the above figure you notice the API returns the list of students available in class ‘English’.
 
Let’s check the details in Google classroom dashboard
 
 
 
From the above figure you can notice for the classroom English it is showing 1 active student from the list.
 
Reference
 
https://developers.google.com/classroom/quickstart/dotnet
 
Summary
 
We have gone through,
 
 • Adding the roaster scope to fetch the student list from the google classroom.
 • Added the function to fetch the student list based on the selected class from our application
 
Click here for the source code.