YouTube API - Oauth2 Flow(OSGI Bundle)

时间:2017-03-09 10:44:22

标签: rest google-api oauth-2.0 osgi-bundle youtube-data-api

我在Apache Felix上开发OSGI Bundle。该套件公开了不同的API来管理YouTube直播活动。捆绑服务将通过REST服务公开,并由具有Web浏览器的用户使用(chrome,safari,mozilla)。

我为帐户生成凭据google(client_secret和client_id)并将其保存在文件中,然后我的代码使用此凭据并正常工作。

我使用此类(在youtube docs上找到)进行身份验证:

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

    // Load client secrets.
    Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/client_secrets.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 ")) {
        LOGGER.info(
                "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}
    FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
    DataStore<StoredCredential> 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.
    return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("myUsername");
}

首次使用日志时我发现了这个:

  

请在浏览器中打开以下地址:     https://accounts.google.com/o/oauth2/auth?client_id=my_client_id&redirect_uri=http://localhost:8080/Callback&response_type=code&scope=https://www.googleapis.com/auth/youtube

直到我没有在浏览器中输入此URL,才会阻止身份验证过程。键入并单击后,该过程正常。

我的问题是:

当用户使用从浏览器调用此服务(api REST将包装此服务)时,在身份验证过程中阻止调用,直到输入和调用url https://accounts.google.com/o/oauth2/auth?client_id=my_client_id&redirect_uri=http://localhost:8080/Callback&response_type=code&scope=https://www.googleapis.com/auth/youtube,如何通知客户端?

我想要对客户端进行透明身份验证。身份验证过程必须只涉及服务器,确切地说是OSGI捆绑包。

提前致谢

1 个答案:

答案 0 :(得分:0)

最后我以这种方式解决了:

我在身份验证流程中添加了2个参数(在GoogleAuthorizationCodeFlow对象中):

.setAccessType("offline")
.setApprovalPrompt("force")

然后只有第一次需要用户确认,并且令牌将自动从API流程刷新(如果将过期)