Google+ OAuth API store and retrieve tokens after first login and authorization

前端 未结 2 575
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 04:00

I have read the documentation, examples and tutorials of how to use the Google API, I have a mini-app running already that shows your latest activities and information, but

相关标签:
2条回答
  • 2021-01-03 04:05

    If you'd like Google to skip the authorization prompt for people who have already authorized your application, add this code in your configuration block at the top:

    $client->setAccessType("online");
    $client-> setApprovalPrompt("auto");
    

    There's one catch with this solution: you will not receive a refresh token when you complete your OAuth dance. This means that your users will be redirected to Google's authentication service every time their access token expires in order to fetch a new one. This will happen roughly every hour.

    Background Info

    By default the PHP client library is configured to provide offline access. You can see this in the source code. When this mode is enabled the OAuth flow will yield a refresh token that can be used to request new access tokens as needed. You may not even notice this happening. The PHP client library takes care of most of this for you.

    This refresh token comes at a cost, though. You are responsible for storing it. If you lose it, your user must re-authorize your application for you to be issued another one. The way you store it depends a lot on the details of your implementation. Session data is a reasonable way to do this if you can make it durable enough.

    0 讨论(0)
  • 2021-01-03 04:27

    This is an old question but it seems to me the answer was not complete.

    The accepted answer works in a way that the user does go through the Google Auth server, just don't see the Auth screen. The question was about storing the token and use it again without sending the user to the Google Server.

    So if that's what you want to do (and it will also allow you to access user data even when they are not currently using your app), all you need to do is ask for an access token that includes a refresh token.

    You do this by using offline access type (which by the way is not the default anymore) - for example in php: $client->setAccessType("offline");.

    Just keep in mind that the access token you receive will include the refresh token only in the first initial authorization by the user, so that's what you need to store.

    Then you can just use that access token with the client, even when it is expired, and the client will take care of refreshing it and getting a new one.

    Hope that helps, Amos

    0 讨论(0)
提交回复
热议问题