简体   繁体   中英

Check if OAuth 2.0 is already authorized

I have implemented application in which I use Google Gmail API to forward emails. But in order to do so, I must be OAuth 2.0 authorized. How to check if I have completed authorization for specific device?

For example, I download app, select account and I want to grant permission to send emails on the beginning because it's a mandatory action. My way is to try to send email and if it fails, I will get onCancelled() in AsyncTask so I can handle GoogleAuthException and acquire error (mLastError). This is bad idea, it would be much simpler to check if authorized or not.

I need to send a fake email , in order to get UserRecoverableAuthIOException, and then I handle it and authorize. After that, everything works fine.

activity.startActivityForResult((UserRecoverableAuthIOException) mLastError).getIntent(), MainActivity.REQUEST_AUTHORIZATION);

I select ALLOW and APIs work great.

I can save flag that app is authorized in shared preferences but if I reinstall app, my device is still authorized, and I do not have information about that.

So I must use curl https://accounts.google.com/o/oauth2/revoke?token=XXX to remove token.

Why my app is still authorized? And why I must revoke token manually? It has some time to expire, but how to check that? If it's not expired, I can continue to use my app without authorizing again. Any ideas?

Thanks

You should catch the UserRecoverableAuthException and in the catch block, you recover the Intent from the exception by calling UserRecoverableAuthException#getIntent(). Start that intent to take user to the OAuth2 permission page for your app.

For these types of server-to-server interactions you need a service account, which is an account that belongs to your application instead of to an individual end-user. Your application calls Google APIs on behalf of the service account, and user consent is not required.

A service account's credentials, which you obtain from the Google API Console, include a generated email address that is unique, a client ID, and at least one public/private key pair. You use the client ID and one private key to create a signed JWT and construct an access-token request in the appropriate format. Your application then sends the token request to the Google OAuth 2.0 Authorization Server, which returns an access token. The application uses the token to access a Google API. When the token expires, the application repeats the process.

Please check the Oauth documentation here: https://developers.google.com/identity/protocols/OAuth2#expiration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM