Upload videos to Youtube from my web server in Java

这一生的挚爱 提交于 2019-12-03 09:16:30

In general, starting at API V3, Google prefers OAuth2 over other mechanism, and uploading a video (or any other action that modifies user data) requires OAuth2.

Fortunately, there is a special kind of token called refresh token to the rescue. Refresh token does not expire like normal access token, and is used to generate normal access token when needed. So, I divided my application into 2 parts:

  • The 1st part is for generating refresh token, which is a Java desktop app, meant to be run by a user on a computer. See here for sample code from Google.
  • The 2nd part is is part of my web application, which uses a given refresh token to create a credential object.

Here is my implementation in Scala, which you can adapt to Java version easily:

For generating a refresh token, you should set the accessType to offline for the authorization flow. Note: if a token already exists on your system, it won't try to get new token, even if it does not have refresh token, so you also have to set approval prompt to force:

def authorize(dataStoreName: String, clientId: String, clientSecret: String): Credential = {

    val builder = new GoogleAuthorizationCodeFlow.Builder(
      HTTP_TRANSPORT,
      JSON_FACTORY,
      clientId,
      clientSecret,
      Seq(YouTubeScopes.YOUTUBE_UPLOAD)
    )

    val CREDENTIAL_DIRECTORY = s"${System.getProperty("user.home")}/.oauth-credentials"
    val fileDataStoreFactory = new FileDataStoreFactory(new java.io.File(CREDENTIAL_DIRECTORY))
    val dataStore: DataStore[StoredCredential] = fileDataStoreFactory.getDataStore(dataStoreName)

    builder.setCredentialDataStore(dataStore).setAccessType("offline").setApprovalPrompt("force")

    val flow = builder.build()

    val localReceiver = new LocalServerReceiver.Builder().setPort(8000).build()

    new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user")
}

val credential = authorize(dataStore, clientId, clientSecret)
val refreshToken = credential.getRefreshToken

For using the refresh token on the server, you can build a credential from a refresh token:

def getCredential = new GoogleCredential.Builder()
    .setJsonFactory(JSON_FACTORY)
    .setTransport(HTTP_TRANSPORT)
    .setClientSecrets(clientId, clientSecret)
    .build()
    .setRefreshToken(refreshToken)

I have have bypassed the whole AuthorizationCodeInstalledApp authorize() method and created a new subclass which bypasses the jetty server implementation process. The methods are as follows

  1. getAuthorizationFromStorage : Get access token from stored credentials.
  2. getAuthorizationFromGoogle : Get the authentication with the credentials from Google creates the url that will lead the user to the authentication page and creating a custom defined name-value pair in the state parameter. The value should be encoded with base64 encoder so we can receive the same code redirected from google after authentication.
  3. saveAuthorizationFromGoogle : Save the credentials that we get from google.

    • Create the GoogleAuthorizationCodeFlow object from the credentialDatastorfrom the response received from the google after authentication.
    • Hit google to get the permanent refresh-token that can be used to get the accesstoken of the user any time .
    • Store the tokens like accesstoken and refreshtoken in the filename as userid

Checkout the code Implementation here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!