简体   繁体   English

适用于Java的Cloud Storage API客户端库:-400错误的请求:“错误”:“ unauthorized_client”

[英]Cloud Storage API Client Library for Java: - 400 Bad Request : “error” : “unauthorized_client”

i am trying to build a connector to download files from google cloud. 我试图建立一个连接器,以从Google Cloud下载文件。 for this i am using Cloud Storage API Client Library for Java (v1beta2-rev23-1.17.0-rc) 为此,我正在使用Java的Cloud Storage API客户端库(v1beta2-rev23-1.17.0-rc)

  1. I am using oAuth2.0 and followed steps mentioned in cloud console help. 我正在使用oAuth2.0,并遵循了云控制台帮助中提到的步骤。
  2. Verified that i can access my bucket via gsutil and api explorer. 验证我可以通过gsutil和api Explorer访问我的存储桶。
  3. Downloaded the code from samples ,added my client_secrets.json and added a line to list my buckets content. 从示例下载了代码,添加了我的client_secrets.json并添加了一行以列出我的存储桶内容。

i am getting error 我遇到错误

"400 Bad Request : "error" : "unauthorized_client" “ 400错误的请求:”错误“:” unauthorized_client“

and not able to download the files. 并且无法下载文件。

Code is 代码是

https://gist.github.com/yashk/9226613 https://gist.github.com/yashk/9226613

        /**
     * Main class for the Cloud Storage API command line sample.
     * Demonstrates how to make an authenticated API call using OAuth 2 helper classes.
     */
    public class StorageSample {

      /**
       * Be sure to specify the name of your application. If the application name is {@code null} or
       * blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
       */
      private static final String APPLICATION_NAME = "MyCompnay/1.0";

      /** Directory to store user credentials. */
      private static final java.io.File DATA_STORE_DIR =
          new java.io.File(System.getProperty("user.home"), ".store/storage_sample");

      /**
       * Global instance of the {@link DataStoreFactory}. The best practice is to make it a single
       * globally shared instance across your application.
       */
      private static FileDataStoreFactory dataStoreFactory;

      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

      /** Global instance of the HTTP transport. */
      private static HttpTransport httpTransport;

      @SuppressWarnings("unused")
      private static Storage client;

      /** Authorizes the installed application to access user's protected data. */
      private static Credential authorize() throws Exception {
        // load client secrets
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(StorageSample.class.getResourceAsStream("/client_secrets.json")));
        if (clientSecrets.getDetails().getClientId().startsWith("Enter") ||
            clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
          System.out.println(
              "Overwrite the src/main/resources/client_secrets.json file with the client secrets file "
              + "you downloaded from the Quickstart tool or manually enter your Client ID and Secret "
              + "from https://code.google.com/apis/console/?api=storage#project:<project_id> "
              + "into src/main/resources/client_secrets.json");
          System.exit(1);
        }

        // Set up authorization code flow.
        // Ask for only the permissions you need. Asking for more permissions will
        // reduce the number of users who finish the process for giving you access
        // to their accounts. It will also increase the amount of effort you will
        // have to spend explaining to users what you are doing with their data.
        // Here we are listing all of the available scopes. You should remove scopes
        // that you are not actually using.
        Set<String> scopes = new HashSet<String>();
        scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
        scopes.add(StorageScopes.DEVSTORAGE_READ_ONLY);
        scopes.add(StorageScopes.DEVSTORAGE_READ_WRITE);

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            httpTransport, JSON_FACTORY, clientSecrets, scopes)
            .setDataStoreFactory(dataStoreFactory)
            .build();
        // authorize
        return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
      }

      public static void main(String[] args) {
        try {
          // initialize the transport
          httpTransport = GoogleNetHttpTransport.newTrustedTransport();

          // initialize the data store factory
          dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

          // authorization
          Credential credential = authorize();
          // set up global Storage instance
          client = new Storage.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();

          client.objects().list("<bucket_id>").executeAndDownloadTo(System.out);

        } catch (IOException e) {
          System.err.println(e.getMessage());
        } catch (Throwable t) {
          t.printStackTrace();
        }
        System.exit(1);
      }
    }
 }

Error Log is https://gist.github.com/yashk/9226613 错误日志为https://gist.github.com/yashk/9226613

Feb 26, 2014 9:28:05 AM com.google.api.client.http.HttpRequest execute
CONFIG: -------------- REQUEST  --------------
POST https://accounts.google.com/o/oauth2/token
Accept-Encoding: gzip
User-Agent: Google-HTTP-Java-Client/1.17.0-rc (gzip)
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 208

Feb 26, 2014 9:28:05 AM com.google.api.client.http.HttpRequest execute
CONFIG: curl -v --compressed -X POST -H 'Accept-Encoding: gzip' -H 'User-Agent: Google-HTTP-Java-Client/1.17.0-rc (gzip)' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -d '@-' -- 'https://accounts.google.com/o/oauth2/token' << $$$
Feb 26, 2014 9:28:05 AM com.google.api.client.util.LoggingByteArrayOutputStream close
CONFIG: Total: 208 bytes
Feb 26, 2014 9:28:05 AM com.google.api.client.util.LoggingByteArrayOutputStream close
CONFIG: grant_type=refresh_token&refresh_token=<removed_for_sec>&client_id=<removed_for_sec>&client_secret=<removed_for_sec>
Feb 26, 2014 9:28:05 AM com.google.api.client.http.HttpResponse <init>
CONFIG: -------------- RESPONSE --------------
HTTP/1.1 400 Bad Request
Expires: Fri, 01 Jan 1990 00:00:00 GMT
X-XSS-Protection: 1; mode=block
Alternate-Protocol: 443:quic
Server: GSE
X-Content-Type-Options: nosniff
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
X-Frame-Options: SAMEORIGIN
Date: Wed, 26 Feb 2014 09:28:01 GMT
Transfer-Encoding: chunked
Content-Encoding: gzip
Content-Type: application/json

Feb 26, 2014 9:28:05 AM com.google.api.client.util.LoggingByteArrayOutputStream close
CONFIG: Total: 37 bytes
Feb 26, 2014 9:28:05 AM com.google.api.client.util.LoggingByteArrayOutputStream close
CONFIG: {
  "error" : "unauthorized_client"
}
400 Bad Request
{
  "error" : "unauthorized_client"
}

figured this out with help of our google corporate contact - 在我们的Google公司联系人的帮助下找到了答案-

in authorize method 授权方法

instead of 代替

return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
      }

use your google account user name from the cloud console 在云端控制台中使用您的Google帐户用户名

return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("myemail@mycompany.com");
      }

after this change if you run the code , it will popup a browser window and ask you authorize access to the project and bingo! 更改之后,如果您运行代码,它将弹出一个浏览器窗口,并询问您是否授权访问该项目和bingo!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Oauth2客户端凭据授予的Java应用程序的Active Directory身份验证会产生“unauthorized_client”错误 - Active Directory Authentication for java application with Oauth2 client credential grant produces “unauthorized_client” error 带有 Java 客户端的 OData 错误请求 400 - OData Bad Request 400 with Java Client 获得 400 - 错误请求 Java 客户端 - Getting 400 - Bad Request Java Client 带有Gradle的Google云端存储Java客户端库 - Google Cloud Storage Java Client Library with Gradle 用于获取访问令牌的Google oauth java客户端失败,并显示“400 Bad Request {”error“:”invalid_request“}” - Google oauth java client to get an access token fails with “400 Bad Request { ”error“ : ”invalid_request“ }” 用于获取访问令牌的Google oauth java客户端失败,并显示“400 Bad Request {”error“:”invalid_request“}” - Google oauth java client to get an access token fails with “400 Bad Request { ”error“ : ”invalid_request“ }” 错误“ 400错误的请求”客户端发送的请求在语法上不正确 - Error “400 Bad Request” The request sent by the client was syntactically incorrect 使用java客户端通过rest api上传文件时出现400错误请求 - 400 bad request when using java client to upload file through rest api Parse.com REST API错误代码400:从Java HTTP请求到云功能的错误请求 - Parse.com REST API Error Code 400: Bad Request from Java HTTP Request to Cloud Function com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request Invalid Grant java Console Application - com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request Invalid Grant java Console Application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM