Google API - Oauth 2.0 Auth token flow

纵然是瞬间 提交于 2020-02-06 07:19:21

问题


Context --

  • I am building a web application that uses the Google Cal and Google+ API.
  • I will need to obtain a refresh token, since once a user authenticates with the site/app, some of the calls happen behind the scenes after they have logged in (and many of them happen after 1 hour, of which the initial access_token is valid for)

As I understand it, here is the flow I must follow:

  1. Register a Web Application API through Google console - done.
  2. Prompt the user to authenticate with my application, done through a call using the following config vars:

  var config = {
    'client_id': MY_CLIENT_ID',
    'scope': 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email',
    'response_type': 'code',
    'access_type': 'offline'
  };
  1. Then, using the Google object returned through the auth() call above, make another call to get the access_token and refresh_token.

https://developers.google.com/accounts/docs/OAuth2WebServer#refresh

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

code=CODE_RETURNED
client_id=CLIENT_ID_RETURNED
client_secret=API_CLIENT_SECRET
redirect_uri=API_REDIRECT_API
grant_type=authorization_code

Yet, when I try to run this call I always get some type of error. Right now I am stuck getting the following:

{
  error: "redirect_uri_mismatch"
}

I have the following listed as my redirect uri both on the Google API settings page, and in code:

http://localhost/

Any advice from someone that has worked with this flow before? Do I need to set up something differently for obtaining a refresh token?


回答1:


The issue as to why this whole process was failing was because I was not including the 'redirect_uri' in my initial call to get a code.

I should have had:

var config = {
    'client_id': MY_CLIENT_ID',
    'scope': 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email',
    'response_type': 'code',
    'access_type': 'offline',
    'redirect_uri': MY_REDIRECT_URI
 };

Then, that redirect_uri was hit with data, and I set up a simple node route to listen, generate, and then store the access and refresh tokens for each user that authenticated.



来源:https://stackoverflow.com/questions/26621862/google-api-oauth-2-0-auth-token-flow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!