DEV Community

Trollgen Studios
Trollgen Studios

Posted on

Google Sign In and Google Calendar API tutorial with client and server (iOS and Pyhton backend)

I'll briefly show you how to do 2 things:
1) Logging in on iOS with Google
2) Getting the access and refresh tokens

Here are the steps:

Go to Google API and enable Google Calendar
Create OAuth Consent Screen
Generate a OAuth for your frontend (iOS / Android / Web)
Integrate sign in with Firebase
Make sure to add scope on sign in with Google (this is for iOS but similar for other frontends)

let additionalScopes = [
                "https://www.googleapis.com/auth/calendar.readonly",
                "https://www.googleapis.com/auth/userinfo.email",
                "https://www.googleapis.com/auth/userinfo.profile",
            ]
            let result2 = try await gidSignInResult.user.addScopes(additionalScopes, presenting: getRootViewController())
Enter fullscreen mode Exit fullscreen mode

Then a serverAuthCode will be returned. Call a backend POST route to obtain access and refresh tokens (more details here: https://developers.google.com/identity/sign-in/ios/offline-access)

Use Google’s client libraries on backend to generate

credentials = client.credentials_from_clientsecrets_and_code(
            CLIENT_SECRET_FILE,
            ['https://www.googleapis.com/auth/calendar.readonly'],
            auth_code,
            redirect_uri="" # this must be there!
        )
if gcal_access_token:
  creds = Credentials.from_authorized_user_info(
   gcal_access_token,
   scopes=CALENDAR_SCOPES
  )
  print(creds.to_json())
 if not creds or not creds.valid:
  # If the credentials are expired, refresh them
  if creds and creds.expired and creds.refresh_token:
   creds.refresh(Request())
   print(creds.to_json())
Enter fullscreen mode Exit fullscreen mode
  1. You can then use the creds with the library to get events:

   calendar_event_result = service.events().list(
    calendarId="primary",
    singleEvents=False,
    orderBy="updated",
   ).execute()
Enter fullscreen mode Exit fullscreen mode

I spent at least 10 hours of my life on navigating this maze due to improper documentation on how to authenticate with google sign in on frontend and then use Google Calendar API on backend, so hope this helps someone!

BY the way, if on the server you get a redirect_uri_mismatch bug, make sure to enable your localhost / production urls and then also have redirect_uri="" above

Top comments (0)