Geeting 403 错误:PERMISSION_DENIED 尝试在 Java 中使用 People Api 创建联系人时

问题描述

我正在尝试使用 People API 创建联系人。但是我在调​​用 API 时遇到错误

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,"errors" : [ {
    "domain" : "global","message" : "Insufficient Permission","reason" : "insufficientPermissions"
  } ],"message" : "Request had insufficient authentication scopes.","status" : "PERMISSION_DENIED"
}

我的代码是:

public class PeopleQuickstart {
    private static final String APPLICATION_NAME = "Google People API Java Quickstart";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";
 
    private static final List<String> ScopES = Arrays.asList(PeopleServiceScopes.CONTACTS);
    private static final String CREDENTIALS_FILE_PATH = "credentials.json";

        private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
         
        InputStream in = PeopleQuickstart.class.getResourceAsstream(CREDENTIALS_FILE_PATH);
        if (in == null) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,new InputStreamReader(in));
         
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,JSON_FACTORY,clientSecrets,ScopES)
                        .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                        .setAccesstype("offline").build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8080).build();
        return new AuthorizationCodeInstalledApp(flow,receiver).authorize("user");
    }

    public static void main(String... args) throws IOException,GeneralSecurityException {
         
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
         
        PeopleService peopleService = new PeopleService.Builder(HTTP_TRANSPORT,getCredentials(HTTP_TRANSPORT)).setApplicationName(APPLICATION_NAME).build();

        Person contactToCreate = new Person();
        List names = new ArrayList<>();
        names.add(new Name().setGivenname("John").setFamilyName("Doe"));
        contactToCreate.setNames(names);

        Person createdContact = peopleService.people().createContact(contactToCreate).execute();
    }

即使我尝试将 Scop 更改为私有静态最终列表 ScopES = Arrays.asList(PeopleServiceScopes.CONTACTS_READONLY) 但是遇到了同样的问题...

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)