服务器端应用程序上的Google OAuth 2.0

时间:2016-04-15 14:41:50

标签: oauth-2.0

我正在尝试创建一个运行命令行的Java应用程序,从shell脚本运行,在cron作业中运行。在这种情况下,我不会让用户在场同意允许在浏览器中访问。此应用程序将查询目录,并将此目录中的视频上传到YouTube。我是YouTube api和Oauth2.0的新手。在我所做的所有研究中,我看到了很多关于如何完成我想要做的事情的相互矛盾的信息。

这是我的代码。请告诉我你哪里出错了。提前谢谢!

public static Credential authorize(List scopes,String credentialDatastore)抛出IOException {

    // Load client secrets.
    //Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/main/resources/client_secrets.json"));
    Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/main/resources/client_secret_file.apps.googleusercontent.com.json"));
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);

    // Checks that the defaults have been replaced (Default = "Enter X here").
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        System.out.println(
                "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential "
                        + "into src/main/resources/client_secrets.json");
        System.exit(1);
    }

    // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
    // THIS IS WHERE I NEED TO CHANGE, TO WORK WITH THIS APP!!!!
   // FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
    FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File("." + "/" + CREDENTIALS_DIRECTORY));
    DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

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

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

    // Authorize.
    try {
        Credential returnCreds = new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("xxxxxxxxxxxxxxxxxxx"); 
        returnCreds.refreshToken();

        return returnCreds;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // if not authorized, will return a null credential
    return null;
}

1 个答案:

答案 0 :(得分:0)

看起来非常像这个帖子有很多我要问的内容:

Does Google OAuth2.0 support an OAuth-flow for a Resource Owner Password Credential Flow?

还没有完成这个实现,但它确实看起来像一个好的领导!