如何 google oauth 到 api?我的例子不工作

How to google oauth to an api? My example is not working

我正在尝试为 google 云构建

撰写这篇文章
https://cloud.google.com/endpoints/docs/openapi/service-account-authentication

我猜想使用我在该示例中生成密钥的服务帐户电子邮件,并且对于 Audient,我输入了“”(这可能是它不起作用的原因?)。我不知道也找不到世界上可以为观众展示的东西。

除了下面的代码之外,我还尝试将观众设置为“https://cloudbuild.googleapis.com”,但也没有用

我的代码如下...

public class GenToken {
    public static void main(String[] args) throws IOException {
        Duration d = Duration.ofDays(365);
        String tok = generateJwt("/Users/dean/workspace/order/java/googleBuild/orderly-gcp-key.json",
                "mycloudbuilder@order-gcp.iam.gserviceaccount.com", "", d.toSeconds());

        System.out.println("tok="+tok);

        URL url = new URL("https://cloudbuild.googleapis.com/v1/projects/order-gcp/builds");
        makeJwtRequest(tok, "GET", url);

    }

    public static String generateJwt(final String saKeyfile, final String saEmail,
                                     final String audience, final long expiryLength)
            throws FileNotFoundException, IOException {

        Date now = new Date();
        Date expTime = new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(expiryLength));

        // Build the JWT payload
        JWTCreator.Builder token = JWT.create()
                .withIssuedAt(now)
                // Expires after 'expiraryLength' seconds
                .withExpiresAt(expTime)
                // Must match 'issuer' in the security configuration in your
                // swagger spec (e.g. service account email)
                .withIssuer(saEmail)
                // Must be either your Endpoints service name, or match the value
                // specified as the 'x-google-audience' in the OpenAPI document
                .withAudience(audience)
                // Subject and email should match the service account's email
                .withSubject(saEmail)
                .withClaim("email", saEmail);

        // Sign the JWT with a service account
        FileInputStream stream = new FileInputStream(saKeyfile);
        ServiceAccountCredentials cred = ServiceAccountCredentials.fromStream(stream);
        RSAPrivateKey key = (RSAPrivateKey) cred.getPrivateKey();
        Algorithm algorithm = Algorithm.RSA256(null, key);
        return token.sign(algorithm);
    }

    /**
     * Makes an authorized request to the endpoint.
     */
    public static String makeJwtRequest(final String signedJwt, String method, final URL url)
            throws IOException, ProtocolException {

        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod(method);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "Bearer " + signedJwt);

        InputStreamReader reader = new InputStreamReader(con.getInputStream());
        BufferedReader buffReader = new BufferedReader(reader);

        String line;
        StringBuilder result = new StringBuilder();
        while ((line = buffReader.readLine()) != null) {
            result.append(line);
        }
        buffReader.close();
        return result.toString();
    }
}

orderly-gcp-key.json里面有这些属性

{
    "type": "service_account",
    "project_id": "myproj",
    "private_key_id": "xxxxxxxx",
    "private_key": "-----BEGIN PRIVATE KEY-----\nasdfsd\n-----END PRIVATE KEY-----\n",
    "client_email": "build-ci-mine@myproj.iam.gserviceaccount.com",
    "client_id": "1167333552",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/build-ci-mine%40myproj.iam.gserviceaccount.com"
}

哎呀,我的编辑没有发布:(。这是错误

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 401 for URL: https://cloudbuild.googleapis.com/v1/projects/orderly-gcp/builds
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1919)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250)
at com.orderlyhealth.auth.websecure.GenToken.makeJwtRequest(GenToken.java:71)
at com.orderlyhealth.auth.websecure.GenToken.main(GenToken.java:26)

希望我能更好地理解!!

当您尝试访问 Google API 时,您必须使用访问令牌。我有 2 个代码片段给你。

使用Google Http客户端

        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
        HttpRequestFactory factory = new NetHttpTransport().createRequestFactory(new HttpCredentialsAdapter(credentials));
        HttpRequest request = factory.buildGetRequest(new GenericUrl("https://cloudbuild.googleapis.com/v1/projects/gbl-imt-homerider-basguillaueb/builds"));
        HttpResponse httpResponse = request.execute();
        System.out.println(CharStreams.toString(new InputStreamReader(httpResponse.getContent(), Charsets.UTF_8)));

使用纯java连接

        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();

        HttpURLConnection con = (HttpURLConnection) new URL("https://cloudbuild.googleapis.com/v1/projects/gbl-imt-homerider-basguillaueb/builds").openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "Bearer " + credentials.refreshAccessToken().getTokenValue());

        InputStreamReader reader = new InputStreamReader(con.getInputStream());
        BufferedReader buffReader = new BufferedReader(reader);

        String line;
        StringBuilder result = new StringBuilder();
        while ((line = buffReader.readLine()) != null) {
            result.append(line);
        }
        buffReader.close();
        System.out.println(result.toString());

可以依赖平台环境。在本地,执行 gcloud auth application-default login 将您的凭据设置为默认默认凭据。在 GCP 上,由于 GoogleCredentials.getApplicationDefault();

方法,使用组件标识(默认服务帐户或您在创建组件时定义的服务帐户)

你的依赖管理需要这个(在 maven 中)

        <dependency>
            <groupId>com.google.auth</groupId>
            <artifactId>google-auth-library-oauth2-http</artifactId>
            <version>0.20.0</version>
        </dependency>

这是否解决了您的问题?