Search code examples
ruby-on-railsomniauthgmail-apigoogle-api-clientnet-http

Net::HTTPUnauthorized when trying to access Gmail API from RAILS 4


I have set up Google authorization in my Rails 4 app and it works as expected. Now I would like to retrieve authorized user emails using Gmail API, but I am receiving #<Net::HTTPUnauthorized:0x0055ed1f7f8d68> error in browser as response to my GET request.

In devs console I have enabled all neccesary APIs.

My code:

initializers/omniauth.rb

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, Rails.application.secrets.client_id, Rails.application.secrets.client_secret, {scope: ['email',
    'https://www.googleapis.com/auth/gmail.modify'],
    access_type: 'offline', client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}}
end

User.rb

  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.email = auth.info.email
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end

In my controller:

 def mail
   require 'net/http'
   access_token =  current_user.oauth_token
   e = current_user.email
   u = "https://www.googleapis.com/gmail/v1/users/#{e}/messages? maxResults=50&key=#{access_token}"
   url = URI.parse(u)
   req = Net::HTTP::Post.new(url.request_uri)
   http = Net::HTTP.new(url.host, url.port)
   http.use_ssl = (url.scheme == "https")
   response = http.request(req)
   @resbody = response
end

In my view

<%= @resbody %>

Installed gems:

gem "omniauth-google-oauth2", "~> 0.2.1"
gem "google-api-client"

When I tried to execute

curl https://www.googleapis.com/gmail/v1/users/my-email/messages&access_token=ya29.Ci .... A
[1] 6687

I received such message:

 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

Question: I don't get it. If I am authorized with Google Account and saved my access token in database and later retrieving it to use with Gmail API it is not working?

What could be that I am doing completely wrong ?

Thanks in advance.


Solution

  • Found problems with my code:

    req = Net::HTTP::Post.new(url.request_uri) changed to req = Net::HTTP::Get.new(url.request_uri)

    and

    @resbody = response to @resbody = response.body

    Now I can see retrieved mails :)