google-oauthgoogle-classroom

Google Classroom iframe, compare login_hint with signed in user


The Test Plan doc for Google Classroom Add-ons says

■ If you receive the login_hint query parameter, you must display a Google-branded sign-in button if the login_hint query parameter does not match the currently signed in user’s ID in Classroom.

This makes sense, but I don't understand how you get the currently signed in user's ID in Classroom. The Python code in walkthrough 3 doesn't seem to do this, unless I'm missing something.

What's the proper way to get the currently signed in user's ID so I can make this comparison with login_hint?


Solution

  • You can fetch the user's ID with the userinfo service. Something like:

    user_info_service = googleapiclient.discovery.build(
        serviceName="oauth2", version="v2", credentials=credentials)
    
    user_info = user_info_service.userinfo().get().execute()
    
    id = user_info.get("id")
    

    This is done in the walkthrough, but perhaps not following that wording exactly. See the stored credentials section. I think rather than checking if the IDs match, the example app flow is more like this:

    1. The first time a user opens the add-on, you might not receive a login_hint if the user hasn't complete the authentication/authorization flow for your app before.
    2. Sign them in now to get their auth token, then use that token to make a call to the userinfo service to get the user's ID, name, picture, whatever you need.
    3. Save the user info to your database, probably keyed on their ID.

    Now later on another visit...

    1. You receive the login_hint because this user has signed in before.
    2. Try to look up the user in your database based on that login_id.
    3. If the lookup is successful, then load that user's details into the session. If it's not, go back to step #1.

    This achieves the same goal, which is ensuring the user coming from Classroom is the one that ends up signed into the add-on, even if you didn't explicitly check for the ID's matching.

    The key concepts with add-ons is that:

    1. For any app that calls Google APIs (like Classroom's API but also Sheets, Docs, Cloud, etc.) you need to put the user through the OAuth flow to authenticate and authorize them (in other words, get their ID and API auth token).
    2. Classroom add-ons will always pass the current Classroom user's ID via login_hint (if they've used your app before), regardless of what user session is currently active in your app.

    You want to avoid the scenario where the add-on opens up for Sally in Classroom, but Timmy was already signed into your app because he was using the browser earlier, and now there's a mix up.