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.
- function start() {
- gapi.load('auth2', function() {
- auth2 = gapi.auth2.init({
- client_id: "Give your client Id",
- scope: 'https://www.googleapis.com/auth/classroom.courses.readonly https://www.googleapis.com/auth/classroom.rosters',
- });
- });
- }
Complete code
- @{
- ViewData["Title"] = "Index";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
- <!DOCTYPE html>
- <html>
- <head>
- <style>
- html {
- font-size: 14px;
- font-family: Arial, Helvetica, sans-serif;
- }
- </style>
- <title></title>
- <script src="https://kendo.cdn.telerik.com/2019.3.1023/js/jquery.min.js"></script>
- <script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
-
- </head>
- <body>
- <div id="example">
-
- <button id="btnSignIn" class="btn-default" onclick="GoogleAuthenticationPage()">Sign in</button>
- <button class="btn-default" id="googleAuth">Get Course</button>
- <div id="grid"></div>
- <br/>
- <button type="button" id="btnSelectRow" value="GetValue" class="k-button">Get Student</button>
- <br/>
- <div id="StudentList"></div>
- <script type="text/javascript">
- function start() {
- gapi.load('auth2', function () {
- auth2 = gapi.auth2.init({
- client_id: "1070617910386-e614kn8nptnf7kpec2fmksoaa3t610gd.apps.googleusercontent.com",
- scope: 'https://www.googleapis.com/auth/classroom.courses.readonly https://www.googleapis.com/auth/classroom.rosters',
- });
- });
- }
- 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: "give your client Id Key", client_secret: "give your client secrete key", redirect_uri: 'https://localhost:44357', grant_type: 'authorization_code'
- },
- success: function (response) {
- debugger;
- 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');
- }
- }
- $("#googleAuth").click(function (e) {
- $("#grid").kendoGrid({
- dataSource: {
- type: "json",
- transport: {
- read: "/GoogleClassRoom/GetCourse"
- },
- pageSize: 20
- },
- selectable: "true",
- height: 550,
- toolbar: ["search"],
- columns: [{
- field: "name",
- title: "Name"
- },]
- });
- })
- $("#btnSelectRow").click(function () {
-
- var grid = $("#grid").data("kendoGrid");
- var selectedItem = grid.dataItem(grid.select());
-
- $("#StudentList").kendoGrid({
- dataSource: {
- type: "json",
- transport: {
- read: "/GoogleClassRoom/GetStudents?courseId="+ selectedItem.id
- },
- pageSize: 20
- },
- selectable: "true",
- height: 550,
- columns: [{
- field: "profile.name.fullName",
- title: "Name"
- },]
- });
- })
- </script>
- </div>
- </body>
- </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.
- public List < Student > GetStudents(string courseId) {
- 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 students = new List < Student > ();
- do {
- var request = googleService.Courses.Students.List(courseId);
- request.PageSize = 100;
- request.PageToken = pageToken;
- var response = request.Execute();
- students.AddRange(response.Students);
- pageToken = response.NextPageToken;
- } while (pageToken != null);
- return students;
- }
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.