0

I'm trying to create assignments for students through the google classroom api. However, I've learned admins can not do that, only teachers. So in our code, after creating a new course we're then setting the teacher's email, which is the same as for the admin and adding it to the . However, the code fails when attempting to add the teacher to the course. It says "The caller does not have permission". I'm not sure what extra permissions would be needed and am stuck on this error message.

private static final List<String> SCOPES = 
 Arrays.asList(ClassroomScopes.CLASSROOM_COURSES, 
 ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS, 
 ClassroomScopes.CLASSROOM_COURSEWORK_ME, 
 ClassroomScopes.CLASSROOM_PROFILE_EMAILS,
 ClassroomScopes.CLASSROOM_PROFILE_PHOTOS,
 ClassroomScopes.CLASSROOM_ROSTERS);


    Course course = new Course()
            .setName("10th Grade Biology")
            .setSection("Period 2")
            .setDescriptionHeading("Welcome to 10th Grade Biology")
            .setDescription("We'll be learning about about the structure of living creatures "
                    + "from a combination of textbooks, guest lectures, and lab work. Expect "
                    + "to be excited!")
            .setRoom("301")
            .setOwnerId("me")
            .setCourseState("PROVISIONED");

    course = service.courses().create(course).execute();
    System.out.printf("Course created: %s (%s)\n", course.getName(), course.getId());


    String courseId = course.getId();
    String teacherEmail = "admin@gmail.com";
    Teacher teacher = new Teacher().setUserId(teacherEmail);
    try {
        teacher = service.courses().teachers().create(courseId, teacher).execute();
        System.out.printf("User '%s' was added as a teacher to the course with ID '%s'.\n",
                teacher.getProfile().getName().getFullName(), courseId);
    } catch (GoogleJsonResponseException e) {
        GoogleJsonError error = e.getDetails();
        if (error.getCode() == 409) {
            System.out.printf("User '%s' is already a member of this course.\n", teacherEmail);
        } else {
            throw e;
        }
    }

enter image description here

public class ClassroomQuickstart {

 private static final String APPLICATION_NAME = "Google Classroom API Java Quickstart";
 private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
 private static final String TOKENS_DIRECTORY_PATH = "tokens";


private static final List<String> SCOPES = 
Arrays.asList(ClassroomScopes.CLASSROOM_COURSES, 
ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS, 
ClassroomScopes.CLASSROOM_COURSEWORK_ME, 
ClassroomScopes.CLASSROOM_ROSTERS);


private static final String CREDENTIALS_FILE_PATH = "/credentials.json";


private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = ClassroomQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
    throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
        .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
        .setAccessType("offline")
        .build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
 }


public static void main(String... args) throws IOException, 
GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = 
GoogleNetHttpTransport.newTrustedTransport();
Classroom service = new Classroom.Builder(HTTP_TRANSPORT, JSON_FACTORY, 
getCredentials(HTTP_TRANSPORT))
        .setApplicationName(APPLICATION_NAME)
        .build();

// List the first 10 courses that the user has access to.
ListCoursesResponse response = service.courses().list()
        .setPageSize(10)
        .execute();
List<Course> courses = response.getCourses();
if (courses == null || courses.size() == 0) {
    System.out.println("No courses found.");
} else {
    System.out.println("Courses:");
    for (Course course : courses) {
        System.out.printf("%s\n", course.getName());
    }
 }


 Course course = new Course()
        .setName("10th Grade Biology")
        .setSection("Period 2")
        .setDescriptionHeading("Welcome to 10th Grade Biology")
        .setDescription("We'll be learning about about the structure of living creatures "
                + "from a combination of textbooks, guest lectures, and lab work. Expect "
                + "to be excited!")
        .setRoom("301")
        .setOwnerId("me")
        .setCourseState("PROVISIONED");

course = service.courses().create(course).execute();
System.out.printf("Course created: %s (%s)\n", course.getName(), course.getId());


String courseId = course.getId();
String teacherEmail = "admin@gmail.com";
Teacher teacher = new Teacher().setUserId(teacherEmail);
try {
    teacher = service.courses().teachers().create(courseId, teacher).execute();
    System.out.printf("User '%s' was added as a teacher to the course with ID '%s'.\n",
            teacher.getProfile().getName().getFullName(), courseId);
} catch (GoogleJsonResponseException e) {
    GoogleJsonError error = e.getDetails();
    if (error.getCode() == 409) {
        System.out.printf("User '%s' is already a member of this course.\n", teacherEmail);
    } else {
        throw e;
    }
}



//        CourseWork courseWork = new CourseWork()
//         .setCourseId(course.getId())
//          .setTitle("title")
//          .setWorkType("ASSIGNMENT")
//           .setDescription("desc");

//        service.courses().courseWork().create(course.getId(), courseWork).execute();

}

}

Thank you.

Francislainy Campos
  • 3,462
  • 4
  • 33
  • 81
  • Have you reconsidered using domain admin or impersonating it via service account? related links in the answer below. – NightEye Oct 15 '21 at 17:20

1 Answers1

0

If I'm not mistaken, the requesting user must be a domain administrator or super admin to be able to create a teacher.

Non-super admin users can only access courses they are part of (as teachers, or students), not all courses in the domain.

They can remove students and other teachers from courses they own directly via courses.teachers.delete and courses.students.delete, but they cannot directly add new students and teachers to their courses via courses.teachers.create and courses.students.create. Only domain administrators (Super Admins) can do that. Non-admins must first send an invitation via invitations.create(), and obtain the user's consent.

Although you should be able to impersonate a super admin by using a service account. Samples can be found here

Reference:

NightEye
  • 10,634
  • 2
  • 5
  • 24