问题
My project is to crawl the certain web data and put them into my Google spreadsheet every morning 9:00. And it has to get the authorization to read & write something. That's why the code below is located at the top.
# Google API
CLIENT_ID = blah blah
CLIENT_SECRET = blah blah
OAUTH_SCOPE = blah blah
REDIRECT_URI = blah blah
# Authorization_code
def get_authorization_code
client = Google::APIClient.new
client.authorization.client_id = CLIENT_ID
client.authorization.client_secret = CLIENT_SECRET
client.authorization.scope = OAUTH_SCOPE
client.authorization.redirect_uri = REDIRECT_URI
uri = client.authorization.authorization_uri
Launchy.open(uri)
# Exchange authorization code for access token
$stdout.write "Enter authorization code: "
client.authorization.code = gets.chomp
client.authorization.fetch_access_token!
client.authorization
end
authorization_code = get_authorization_code
access_token = authorization_code.access_token
session = GoogleDrive.login_with_oauth(access_token)
But with this in the code, even though I set up the cron job, I probably have to wake up in the morning and Enter authorization code
to get it done. But I don't want to.
Please tell me how I can solve this problem.
回答1:
Solved thanks to Ruby google_drive gem oAuth2 saving
I needed to get a refresh token and make my code use it like below.
CLIENT_ID = '!!!'
CLIENT_SECRET = '!!!'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
REFRESH_TOKEN = '!!!'
client = Google::APIClient.new
client.authorization.client_id = CLIENT_ID
client.authorization.client_secret = CLIENT_SECRET
client.authorization.scope = OAUTH_SCOPE
client.authorization.redirect_uri = REDIRECT_URI
client.authorization.refresh_token = REFRESH_TOKEN
client.authorization.refresh!
access_token = client.authorization.access_token
session = GoogleDrive.login_with_oauth(access_token)
来源:https://stackoverflow.com/questions/30433380/authorization-issue-with-cron-crawler-inserting-data-into-google-spreadsheet-usi