通过GMail API进行用户模拟的服务器端OAuth

通过GMail API进行用户模拟的服务器端OAuth

问题描述:

我正在尝试执行服务器端OAuth,因此我可以使用我域中的特定用户帐户通过我的应用程序发送电子邮件(因此使用GMail API).

I am trying to perform server-side OAuth so I can use a specific user account in my domain to send emails (hence using GMail API) via my application.

我的是纯粹的服务器端应用程序,我无法通过用户界面执行用户同意".

Mine is a purely server-side app and I cannot perform "user consent" via a UI.

我已经在Google App Engine中创建了一个项目,并获得了服务帐户凭据(P12密钥).

I have created a project in Google App Engine and have obtained service account credentials (P12 key).

我的代码看起来像这样-

My code looks like this -

new GoogleCredential.Builder()
  .setTransport(httpTransport)
  .setJsonFactory(JSON_FACTORY)
  .setServiceAccountId(googleEmailerServiceAccountId)
  .setServiceAccountPrivateKeyFromP12File(new File(googleEmailerServiceAccountPrivateKeyLocation)).setServiceAccountScopes(Collections.singleton(GmailScopes.GMAIL_COMPOSE))
  .setServiceAccountUser("xxx@xxx.com")
  .build()

我已根据 https://developers.google.com/identity/protocols/OAuth2ServiceAccount .

当我尝试从我的应用程序发送电子邮件时,我仍然收到未经授权的401.

And I still get an Unauthorised 401 when I try to send emails from my app.

由于没有明确的Gmail API文档说允许域范围的委派,因此我猜Gmail不允许.

Since there is no explicit documentation for the Gmail API that says it allows domain wide delegation, I am guessing it is not allowed for Gmail.

有什么方法可以通过编程实现这一目标吗?

Is there any way of achieving this programatically?

任何想法将不胜感激. 谢谢!

Any idea would be much appreciated. Thanks!

据我所知,您不能在Gmail中使用服务帐户.服务帐户必须是预先授权的.

As far as I know you cant use a service account with Gmail. Service accounts must be pre authorized.

使用Gmail授权应用

所有对Gmail API的请求必须由经过身份验证的用户授权 用户. Gmail使用 OAuth 2.0 协议对Google进行身份验证 帐户并授权访问用户数据.您也可以使用Google+ 登录以提供使用Google登录"身份验证方法 您的应用.

All requests to the Gmail API must be authorized by an authenticated user. Gmail uses the OAuth 2.0 protocol for authenticating a Google account and authorizing access to user data. You can also use Google+ Sign-in to provide a "sign-in with Google" authentication method for your app.

  1. 与服务"帐户共享一个Google驱动器文件夹.以用户身份将服务帐户电子邮件添加到具有访问权限的google驱动器文件夹中
  2. 与其他用户一样,与服务帐户共享Google日历.

服务帐户无法在所有Google API上使用.据我所知,您无法授予其他用户访问您的Gmail的权限,因此现在可以对服务帐户进行预授权了.

Service accounts don't work on all Google APIs. To my knowledge you cant give another user access to your Gmail so there will be now to pre authorize the service account.

推荐/解决方法/破解

使用相同的客户端ID创建一个虚拟应用,对其进行身份验证以获取刷新令牌,然后在您的应用中使用刷新令牌.

Create a dummy app using the same client id, authenticate it get the refresh token then use the refresh token in your application.