Question

My rails app will allow to create appointments. These appointments should then be exported to each users' google calendar.

I have installed omniauth-google-oauth2, and got my api key, client_id and client_secret for a Web application from Google's API Console.

I can authenticate users with omniauth, and store the access_token, refresh_token and expires_at date into my database, for later use.

When the time comes to export events to each users' google calendar (done in a background job) I get a response of Invalid Credentials.

What am I doing wrong?

Note: I can access user calender immediately after he authorizes in oauth, but not after some time passes.

Code:

sessions_controller

/auth/:provider/callback routes to this method:

auth = request.env["omniauth.auth"]
# Save token of user
current_user.google_auth_token         = auth["credentials"]["token"]
current_user.google_auth_refresh_token = auth["credentials"]["refresh_token"]
current_user.google_auth_expires_at    = Time.at auth["credentials"]["expires_at"]
current_user.save

omniauth config

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"], {
    access_type: 'offline',
    scope: 'userinfo.email,calendar'
  }
end

getting access to create users calendars

client = Google::APIClient.new
client.authorization.refresh_token = app.carer.google_auth_refresh_token
client.authorization.access_token = app.carer.google_auth_token
if client.authorization.refresh_token && client.authorization.expired?
  client.authorization.fetch_access_token!
end
service = client.discovered_api('calendar', 'v3')
result = client.execute(:api_method => service.calendar_list.list)
# results in auth error, Invalid Credentials ...
Was it helpful?

Solution

It seems that I must get a client_ID and client_secret for an Installed Application from the Google API console. That alone fixed the issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top