有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java YouTube数据API V3自动化授权过程,而不是手动干预

我正在使用YouTube数据API V3将视频上传到我的YouTube频道。提供的样本代码中的授权代码需要手动干预授权过程。每次我重新启动服务器时,它都会打开浏览器并询问我的身份验证和权限。对于我的Windows PC来说,这很好,但我将把这段代码部署到一台远程Linux机器上,我只有SSH访问权限

有没有办法使这个过程自动化?类似于使用普通凭证(用户名和密码)访问API或一次性执行此过程(永久身份验证/授权)

我确实读了一些关于这个主题的帖子,这些帖子指向使用刷新令牌


共 (3) 个答案

  1. # 1 楼答案

    您如何存储您的凭据?如果服务器关闭,您的凭据也会随之丢失吗?你可以考虑把它存储在一个外部数据库中,或者如果它是一个Web应用程序,你可以把它存储为cookie。

    刷新令牌只颁发一次(在第一次初始身份验证期间),因此,如果您之前已授权您的帐户,则需要访问您的应用权限并将其删除。然后再次尝试授权,并保存该刷新令牌。如果您正确地保存了刷新令牌(使用cookies/数据库/任何东西),那么您将在请求时获得一个新的访问令牌。使用此方法,您不必每次都重新授权

  2. # 2 楼答案

    也许有点晚了

    1)在Google Developers Console中创建新项目

    2)创建oauth 2.0客户端id。在应用程序类型选择-其他

    3)下载json文件,将其重命名为“client_secret.json”,并将其添加到/resources文件夹(用于Gradle项目)

    4)创建java文件并添加以下代码:

    public class YoutubeAuth {
    
        private static final String CLIENT_SECRETS= "/client_secret.json";
    
        private static final Collection<String> SCOPES =
                Arrays.asList("https://www.googleapis.com/auth/youtube.readonly");
    
        private static FileDataStoreFactory dataStoreFactory;
    
        private static final java.io.File DATA_STORE_DIR =
                new java.io.File(System.getProperty("user.home"), ".store/youtube");
    
        private static final String APPLICATION_NAME = "Custom Application Name";
    
        private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    
        /**
         * Create an authorized Credential object.
         *
         * @return an authorized Credential object.
         * @throws IOException
         */
        private static Credential authorize(final NetHttpTransport httpTransport) throws IOException {
    
           // Load client secrets.
            InputStream in = YoutubeAuth.class.getResourceAsStream(CLIENT_SECRETS);
            GoogleClientSecrets clientSecrets =
                    GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
            // Build flow and trigger user authorization request.
            GoogleAuthorizationCodeFlow flow =
                    new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, SCOPES)
                            .setDataStoreFactory(dataStoreFactory)
                            .build();
            return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
        }
    
        /**
         * Build and return an authorized API client service.
         *
         * @return an authorized API client service
         * @throws GeneralSecurityException, IOException
         */
        public static YouTube getService() throws GeneralSecurityException, IOException {
            final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    
            dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
    
            Credential credential = authorize(httpTransport);
    
    
            return new YouTube.Builder(httpTransport, JSON_FACTORY, credential)
                    .setApplicationName(APPLICATION_NAME)
                    .build();
        }
    
    }
    

    请注意以下代码行:

    private static FileDataStoreFactory dataStoreFactory;
    private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"),".store/youtube");
    

    对于authorize()方法中的此方法:

    .setDataStoreFactory(dataStoreFactory)
    

    对于getService()方法中的此方法:

    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
    
    
    YouTube youtubeService = LfkYoutubeAuth.getService();
    ...
    // some other code
     -
    

    所以你可以像这样使用Youtube服务

  3. # 3 楼答案

    通常我会说你应该使用一个服务帐户,这样你就根本不需要进行身份验证了。但是,YouTube API不支持服务帐户身份验证

    我无法解释为什么重新启动后需要刷新身份验证。您的代码应保存包含刷新令牌的凭据文件。即使在重新启动后,刷新令牌也应继续工作。我猜你的代码有问题

    这是一个Java Quickstart示例,显示了如何保存凭据。它是为人而设的api,而不是Youtube。如果您需要任何帮助,请在Youtube上修改它。服务器重新启动时,不会删除这些凭据

    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
    import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.util.store.FileDataStoreFactory;
    import com.google.api.services.people.v1.PeopleService;
    import com.google.api.services.people.v1.PeopleScopes;
    import com.google.api.services.people.v1.model.ListConnectionsResponse;
    import com.google.api.services.people.v1.model.Person;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.Arrays;
    import java.util.List;
    
    public class Quickstart {
        /** Application name. */
        private static final String APPLICATION_NAME =
            "People API Java Quickstart";
    
        /** Directory to store user credentials for this application. */
        private static final java.io.File DATA_STORE_DIR = new java.io.File(
            System.getProperty("user.home"), ".credentials/people.googleapis.com-java-quickstart");
    
        /** Global instance of the {@link FileDataStoreFactory}. */
        private static FileDataStoreFactory DATA_STORE_FACTORY;
    
        /** Global instance of the JSON factory. */
        private static final JsonFactory JSON_FACTORY =
            JacksonFactory.getDefaultInstance();
    
        /** Global instance of the HTTP transport. */
        private static HttpTransport HTTP_TRANSPORT;
    
        /** Global instance of the scopes required by this quickstart.
         *
         * If modifying these scopes, delete your previously saved credentials
         * at ~/.credentials/people.googleapis.com-java-quickstart
         */
        private static final List<String> SCOPES =
            Arrays.asList(PeopleScopes.CONTACTS_READONLY);
    
        static {
            try {
                HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
                DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
            } catch (Throwable t) {
                t.printStackTrace();
                System.exit(1);
            }
        }
    
        /**
         * Creates an authorized Credential object.
         * @return an authorized Credential object.
         * @throws IOException
         */
        public static Credential authorize() throws IOException {
            // Load client secrets.
            InputStream in =
                Quickstart.class.getResourceAsStream("/client_secret.json");
            GoogleClientSecrets clientSecrets =
                GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
    
            // Build flow and trigger user authorization request.
            GoogleAuthorizationCodeFlow flow =
                    new GoogleAuthorizationCodeFlow.Builder(
                            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                    .setDataStoreFactory(DATA_STORE_FACTORY)
                    .setAccessType("offline")
                    .build();
            Credential credential = new AuthorizationCodeInstalledApp(
                flow, new LocalServerReceiver()).authorize("user");
            System.out.println(
                    "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
            return credential;
        }
    
        /**
         * Build and return an authorized People client service.
         * @return an authorized People client service
         * @throws IOException
         */
        public static PeopleService getPeopleService() throws IOException {
            Credential credential = authorize();
            return new PeopleService.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                    .setApplicationName(APPLICATION_NAME)
                    .build();
        }
    
        public static void main(String [] args) throws IOException {
            PeopleService service = getPeopleService();
    
            // Request 10 connections.
            ListConnectionsResponse response = service.people().connections()
                    .list("people/me")
                    .setPageSize(10)
                    .setPersonFields("names,emailAddresses")
                    .execute();
    
            // Print display name of connections if available.
            List<Person> connections = response.getConnections();
            if (connections != null && connections.size() > 0) {
                for (Person person : connections) {
                    List<Name> names = person.getNames();
                    if (names != null && names.size() > 0) {
                        System.out.println("Name: " + person.getNames().get(0)
                                .getDisplayName());
                    } else {
                        System.out.println("No names available for connection.");
                    }
                }
            } else {
                System.out.println("No connections found.");
            }
        }
    
    }
    

    答:至于您的服务器问题以及如何使其自动化。答案是你不能。无法通过浏览器窗口外的身份验证。您应该在windows pc上进行身份验证,将我提到的凭据文件复制到您的服务器上