gpt4 book ai didi

authentication - 尝试通过服务帐户发送电子邮件获取 com.google.api.client.auth.oauth2.TokenResponseException : 401 Unauthorized

转载 作者:行者123 更新时间:2023-12-03 22:32:32 25 4
gpt4 key购买 nike

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

我已经搜索了互联网,但没有任何效果,我几乎不知所措。

我遵循了 Java 指南,但仍然不断收到 com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized
为什么这个代码片段给我 401 Unauthorized?

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);

这些方法基本上是从 Google 文档中复制/粘贴的:
/**
* 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)

我创建了我的服务帐户并将其设置为域范围的委派,这是我的管理 API 客户端访问范围的屏幕截图:

enter image description here

我错过了什么,我一直得到 401 Unauthorized?

最佳答案

在与 Google 支持人员打了漫长而有用的电话后,我们终于找到了我是否更改了 GmailScopes.all() 的问题。到下面的显式范围然后它起作用了。

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

支持人员不是 100% 确定,但他认为可能是因为我的用户无权访问所有 gmail 范围,而我指定了 GmailScopes.all()在检查我尝试使用哪个范围之前,它是错误的 401 Unauthorized。

关于authentication - 尝试通过服务帐户发送电子邮件获取 com.google.api.client.auth.oauth2.TokenResponseException : 401 Unauthorized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40495315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com