认证 – 尝试通过服务帐户发送电子邮件,获取com.google.api.client.auth.oauth2.TokenResponseException:401未经授权

我有一个Google Apps帐户.我正在尝试使用服务帐户代表用户发送电子邮件.

我已经洗了互联网,没有任何工作,我几乎失去了.

我遵循Java指南,我仍然继续收到com.google.api.client.auth.oauth2.TokenResponseException:401未经授权

为什么这段代码片断给我401未经授权?

JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

            GoogleCredential credential = new GoogleCredential.Builder()
                    .setTransport(httpTransport)
                    .setJsonFactory(JSON_FACTORY)
                    .setServiceAccountId("something@something-something.iam.gserviceaccount.com")
                    .setServiceAccountPrivateKeyFromP12File(new File("path/to/file/myProject.p12"))
                    .setServiceAccountScopes(GmailScopes.all())
                    .setServiceAccountUser("user@mydomain.org")
                    .build();

Gmail gmailService = new Gmail.Builder(httpTransport, JSON_FACTORY, credential)
                    .setApplicationName("My App") // DOES IT MATTER WHAT THIS IS SET TO?
                    .build();

MimeMessage mimeMessage = createEmail("myemail@gmail.com", "user@mydomain.org", "Testing", "hey");
sendMessage(gmailService, "me", mimeMessage);

这些方法基本上是从谷歌文档复制/粘贴:

/**
     * Create a MimeMessage using the parameters provided.
     *
     * @param to email address of the receiver
     * @param from email address of the sender, the mailbox account
     * @param subject subject of the email
     * @param bodyText body text of the email
     * @return the MimeMessage to be used to send email
     * @throws MessagingException
     */
    public static MimeMessage createEmail(String to,
                                          String from,
                                          String subject,
                                          String bodyText)
            throws MessagingException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage email = new MimeMessage(session);

        email.setFrom(new InternetAddress(from));
        email.addRecipient(javax.mail.Message.RecipientType.TO,
                new InternetAddress(to));
        email.setSubject(subject);
        email.setText(bodyText);
        return email;
    }

    /**
       * Send an email from the user's mailbox to its recipient.
       *
       * @param service Authorized Gmail API instance.
       * @param userId User's email address. The special value "me"
       * can be used to indicate the authenticated user.
       * @param email Email to be sent.
       * @throws MessagingException
       * @throws IOException
       */
      public static void sendMessage(Gmail service, String userId, MimeMessage email)
          throws MessagingException, IOException {
        Message message = createMessageWithEmail(email);
        System.out.println("userId = " + userId);
        message = service.users().messages().send(userId, message).execute();

        System.out.println("Message id: " + message.getId());
        System.out.println(message.toPrettyString());
      }

      /**
       * Create a Message from an email
       *
       * @param email Email to be set to raw of message
       * @return Message containing base64url encoded email.
       * @throws IOException
       * @throws MessagingException
       */
      public static Message createMessageWithEmail(MimeMessage email)
          throws MessagingException, IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        email.writeTo(baos);
        String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
        Message message = new Message();
        message.setRaw(encodedEmail);
        return message;
      }

我只是得到这个堆栈跟踪:

com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized
    at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
    at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
    at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:384)
    at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
    at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
    at com.my.services.NotificationServiceTest.testGmailCredential(NotificationServiceTest.java:96)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

我创建了我的服务帐户并设置为域广泛委派,这里是我的Manage API客户端访问范围的屏幕截图:

enter image description here

我失踪了,我保持得到401未经授权?

最佳答案
在与Google支持部长时间,但有帮助的电话之后,我们终于找到了,如果我将GmailScopes.all()更改为下面的显式范围,那么它将起作用.

Collection<String> SCOPES 
    = Collections.unmodifiableCollection(
            Arrays.asList(
                    new String[]{
                            GmailScopes.GMAIL_COMPOSE,
                            GmailScopes.GMAIL_SEND
                    }));

支持者不是100%肯定的,但他认为也许,因为我的用户没有访问所有的Gmail的范围,我指定GmailScopes.all(),它是错误的401未经授权,甚至检查哪个我试图使用的范围.

转载注明原文:认证 – 尝试通过服务帐户发送电子邮件,获取com.google.api.client.auth.oauth2.TokenResponseException:401未经授权 - 代码日志