Ручная аутентификация для Google API в jclouds, отдельное получение токенов

Мне нужно отделить фазу аутентификации от создания API Google, но это очень сложно (для меня) сделать возможным.

Это очень важно, потому что я создаю REST API, который должен получать ранее полученные токены авторизации, а не учетные данные непосредственно от своих пользователей по соображениям безопасности, потому что с помощью токенов я могу установить ограничение на время жизни, как указано в RFC 6750.

У меня есть следующий код:

public class Main { 

    public static void main(String[] args) {      

        // Reads the JSON credential file provided by Google
        String jsonContent = readJson(args[1]);  

        // Pass the credential content
        GoogleComputeEngineApi googleApi = 
                createApi(jsonContent); 
    }

    public static GoogleComputeEngineApi createApi(final String jsonCredentialContent) {
        try {
            Supplier<Credentials> credentialSupplier = new GoogleCredentialsFromJson(
                    jsonCredentialContent);

            ComputeServiceContext context = ContextBuilder
                    .newBuilder("google-compute-engine")
                    .credentialsSupplier(credentialSupplier)
                    .buildView(ComputeServiceContext.class);

            Credentials credentials = credentialSupplier.get();
            ContextBuilder contextBuilder = ContextBuilder
                    .newBuilder(GoogleComputeEngineProviderMetadata.builder()
                            .build())
                    .credentials(credentials.identity, credentials.credential);

            Injector injector = contextBuilder.buildInjector();
            return injector.getInstance(GoogleComputeEngineApi.class);

        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            return null;
        }
    }  
}

Ниже приведен поддельный код с моими потребностями:

public class Main { 

    public static void main(String[] args) {        

        String jsonCredentialContent = readJson(args[1]);  
        String oauthToken = "";

        // First acquires the OAuth token
        if(getAuthenticationType("google-compute-engine").equals("oauth")) {
            oauthToken = getTokenForOAuth(jsonCredentialContent);
        }        

        // Creates the Api with the previously acquired token
        GoogleComputeEngineApi googleApi = 
                createApi(oauthToken); 
    }       

    [...]

}

person lopes    schedule 05.11.2017    source источник


Ответы (1)


Вы можете напрямую использовать API jclouds OAuth для получения токена носителя следующим образом:

GoogleCredentialsFromJson credentials = new GoogleCredentialsFromJson(jsoncreds);

AuthorizationApi oauth = ContextBuilder.newBuilder("google-compute-engine")
    .credentialsSupplier(credentials)
    .buildApi(AuthorizationApi.class);

try {
    long nowInSeconds = System.currentTimeMillis() / 1000;
    Claims claims = Claims.create(
        credentials.get().identity, // issuer
        "https://www.googleapis.com/auth/compute", // write scope
        "https://accounts.google.com/o/oauth2/token", // audience
        nowInSeconds + 60, // token expiration (seconds)
        nowInSeconds // current time (secods)
    );
    Token token = oauth.authorize(claims);
    System.out.println(token);
} finally {
    oauth.close();
}

Получив токен доступа Bearer, вы можете создать с ним контекст jclouds следующим образом:

// Override GCE default Oauth flow (JWT) by the Bearer token flow
Properties overrides = new Properties();
overrides.put(OAuthProperties.CREDENTIAL_TYPE, CredentialType.BEARER_TOKEN_CREDENTIALS.toString());

// It is important to set the proper identity too, as it is used to resolve the GCE project
ComputeServiceContext ctx = ContextBuilder.newBuilder("google-compute-engine")
    .overrides(overrides)
    .credentials(credentials.get().identity, token.accessToken())
    .buildView(ComputeServiceContext.class);

GoogleComputeEngineApi google = ctx.unwrapApi(GoogleComputeEngineApi.class);
person Ignasi Barrera    schedule 06.11.2017
comment
Это сработало! Не могли бы вы также рассказать мне, как я могу получить токен, используя ту же библиотеку jclouds? Я тоже пытаюсь реализовать, но с некоторыми трудностями. - person lopes; 06.11.2017
comment
Я отредактировал ответ, чтобы предоставить полный пример. - person Ignasi Barrera; 07.11.2017
comment
Игнаси, в данный момент я выполняю ту же работу для AWS, не могли бы вы сказать мне, есть ли у вас тестовый код, который делает то же самое, что вы написали выше, только для Amazon? Я много смотрел здесь в коде JClouds и ничего не нашел в Google. - person lopes; 12.07.2018