使用Java创建YouTube事件,无需在浏览器中提示登录。

huangapple go评论94阅读模式
英文:

Create YouTube Event using java without prompting login from browser

问题

我正在尝试使用Java程序在YouTube上创建事件。我可以做到这一点,但它会打开一个浏览器,要求我输入用户登录信息,然后验证并创建.oauth-credentials/createbroadcast文件。我需要一个解决方案,让我的Java代码自己使用一些API密钥/秘密密钥等验证用户,而无需用户干预。

提供代码片段以更好地理解。

// 授权请求。
Credential credential = Auth.authorize(scopes, "createbroadcast");

// 这个对象用于发出YouTube数据API请求。
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
        .setApplicationName("youtube-cmdline-createbroadcast-sample").build();

上面的代码中有一个Auth.authorize方法,如下所示。

public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {

    // 加载客户端密钥。
    Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("./client_secrets.json"));
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);

    // 这将在~/.oauth-credentials/${credentialDatastore}处创建凭据数据存储。
    FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(
            new File(System.getProperty("user.home") + "/.oauth-credentials"));
    DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
            clientSecrets, scopes).setCredentialDataStore(datastore).build();

    // 构建本地服务器并将其绑定到端口8080
    LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

    // 授权。
    // ------------------------问题出在这里-------------------------------------
    // 这个方法调用authorize,它检查“/.oauth-credentials”文件夹下的文件是否小于60秒。
    // 如果不是,它会过期并打开一个浏览器,要求我登录。
    return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
}

我不希望用户干预,我的程序应该处理这个问题,以便在某些事件上我可以执行它并获得授权,而不需要用户提供用户名和密码。(目标是0用户干预)

在上面的代码中,最后一行验证用户并打开浏览器,要求我登录。如何从代码中处理此部分,因为我希望将此代码部署到服务器上,并在我的网页上用户执行操作时在我的帐户中创建此事件。请帮忙。

我目前的发现是com.google.api.client.auth.oauth2.Credential有一个选项来检查refresh token或过期时间。如何设置令牌以避免刷新令牌。授权它的类中的一个方法。

public Credential authorize(String userId) throws IOException {
    try {
      Credential credential = flow.loadCredential(userId);
      if (credential != null
          && (credential.getRefreshToken() != null || credential.getExpiresInSeconds() > 60)) {
        return credential;
      }
      // 在浏览器中打开
      String redirectUri = receiver.getRedirectUri();
      AuthorizationCodeRequestUrl authorizationUrl =
          flow.newAuthorizationUrl().setRedirectUri(redirectUri);
      onAuthorization(authorizationUrl);
      // 接收授权码并将其交换为访问令牌
      String code = receiver.waitForCode();
      TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
      // 存储凭据并返回它
      return flow.createAndStoreCredential(response, userId);
    } finally {
      receiver.stop();
    }
  }

目前它为我返回null的刷新令牌,如何设置以获取令牌而不是验证ExpireTimeinSec。

英文:

I am trying to create Event using Java Program on youtube. I am able to do this but it opens a browser where ask me to enter user login info and then validate and create .oauth-credentials/createbroadcast file.
I need a solution where my java code itself validate user using some API key/secret key etc, wihtout user intervention.

Providing code snippet for more understanding.

 // Authorize the request.
        Credential credential = Auth.authorize(scopes, &quot;createbroadcast&quot;);

        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                .setApplicationName(&quot;youtube-cmdline-createbroadcast-sample&quot;).build();

Above code has Auth.authorize method. which is given below.

public static Credential authorize(List&lt;String&gt; scopes, String credentialDatastore) throws IOException {

	// Load client secrets.
	Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream(&quot;./client_secrets.json&quot;));
	GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);

	// This creates the credentials datastore at
	// ~/.oauth-credentials/${credentialDatastore}
	FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(
			new File(System.getProperty(&quot;user.home&quot;) + &quot;/.oauth-credentials&quot;));
	DataStore&lt;StoredCredential&gt; datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

	GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
			clientSecrets, scopes).setCredentialDataStore(datastore).build();

	// Build the local server and bind it to port 8080
	LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

	**// Authorize.
	// ------------------------Problem is here-------------------------------------
	// This method calls authorize which check if the file under &quot;/.oauth-credentials&quot; folder is less then 60 sec.**
	// If its not it get expires and opens a browser where i requred to login.
	return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize(&quot;user&quot;);
}

return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
I dont want user intervention and my program should handle this so that on some even i can excute it and get it authorized without user asking for userid and passwrod. (Motive is 0 intervention of user)
In the above code last line validate user and opens browser where ask me to login. how can we handle this part from code as i want this code to be deployed on server and on action of user on my webpage i want to create this event in my account.
Kinldy help.

My Finding till now is..
com.google.api.client.auth.oauth2.Credential has open to either check for refreshtoken or expire time. how can we set token and what to set in token to avoid refresh token.
A Method from the class which athorize it.

public Credential authorize(String userId) throws IOException {
try {
  Credential credential = flow.loadCredential(userId);
  if (credential != null
      &amp;&amp; (credential.getRefreshToken() != null || credential.getExpiresInSeconds() &gt; 60)) {
    return credential;
  }
  // open in browser
  String redirectUri = receiver.getRedirectUri();
  AuthorizationCodeRequestUrl authorizationUrl =
      flow.newAuthorizationUrl().setRedirectUri(redirectUri);
  onAuthorization(authorizationUrl);
  // receive authorization code and exchange it for an access token
  String code = receiver.waitForCode();
  TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
  // store credential and return it
  return flow.createAndStoreCredential(response, userId);
} finally {
  receiver.stop();
}

}

As of now it gives me null for get refresh token how can i set so that i get token insted of validating for ExpireTimeinSec.

答案1

得分: 1

以下解决方案目前运行良好,我已经测试了将近10天。
您只需要进行以下代码更改并生成文件。在任何地方使用它。

new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
        clientSecrets, scopes).setAccessType("offline").setCredentialDataStore(datastore).build();

.setAccessType("offline")

到目前为止,即使在1小时后,它仍然有效。将在未来几天进行验证。

[更新]

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
                    clientSecrets, scopes).setAccessType("offline").setCredentialDataStore(datastore).build();

.setAccessType("offline") 上面代码中的这一行运行良好,它将仅刷新授权令牌。用户无需更新由上面的代码生成的授权文件。您可以从本地创建此文件,然后将其放在项目的安全位置并继续使用它。

英文:

Below solution is working fine and i have tested it for almost 10 days now.
You just need below code change and genrate the file. use it anywhere.

new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
        clientSecrets, scopes).setAccessType(&quot;offline&quot;).setCredentialDataStore(datastore).build();

.setAccessType("offline")
Till now its working after 1 hour also. will be validating it for few day.

[Update]

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
					clientSecrets, scopes).setAccessType(&quot;offline&quot;).setCredentialDataStore(datastore).build();

.setAccessType("offline") This line in the above code works fine and it will just refresh the auth token. User never requires to update auth file genratated by above code. you can create this file from local and put it at secure location of your project and keep using it.

huangapple
  • 本文由 发表于 2020年7月29日 23:14:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63156817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定