尝试获取OAuth签名时,我在做什么错?

时间:2019-04-02 22:00:14

标签: java rest api oauth-1.0a

我尝试了oauth 1.0签名生成器的多次迭代。 他们似乎都不起作用。我提供代码以查看是否有人可以 看看我要迷路了。

我一直在寻找包括Stack Overflow这样的帮助,而我 尝试了一些建议。我尝试使用HTTPRequest 就像POSTMAN一样:

 public String GetRequest(String Data) throws IOException {
   OkHttpClient client = new OkHttpClient();
   Request request = new Request.Builder()
     .url(url1)
     .get()
     .addHeader("Content-Type", "application/json")
     .addHeader("Authorization", Data)
     .addHeader("cache-control", "no-cache")
     .build();

   Response response = client.newCall(request).execute();
   return response.body().string();
   } 

我掉了握手。 我已经结合尝试了HttpUrlConnection和两次尝试 下面的OAuth签名:

    url = new URL(url1);
    HttpURLConnection connn = (HttpURLConnection) url.openConnection();
    connn.setRequestProperty("Authorization", token);
    connn.setRequestProperty("Content-Type", "application/json");
    connn.setRequestProperty("cache-control", "no-cache");
    connn.setDoOutput(true);
    connn.setRequestMethod("GET");
    connn.connect();
    int responseCode = connn.getResponseCode();

我用相同的结果尝试了每个-出现“ 403”错误。 我已经使用相同的NONCE将我的签名字符串与POSTMAN进行了比较 和时间戳和我的签名字符串始终是不同的。不应该 一样吗?看来我不是在做同一件事 我生成签名时使用POSTMAN作为order(??)。 提前给了我所有四个代币,并被告知 他们不会过期。

  public static String oauth_consumer_key = "AAAAAAA";  
  public static String oauth_consumer_secret = "BBBBBBBB";
  public static String oauth_request_token = "CCCCCCC"; 
  public static String oauth_request_token_secret = "DDDDD";

  public URL url = null;
  url1 = "https://my url.com/myapi"
  public static String ENC = "UTF-8";

令牌字符串的开头:

  String token = "\"" + "OAuth oauth_consumer_key=" + consumerKeyStr + 
  "," + "oauth_token=" + accessTokenStr + "," + "oauth_signature_method=" 
  + signatureMethod + "," + "oauth_timestamp=" + "\"" + TimeStamp + "\""
  + "," + "oauth_nonce=" + "\"" + XXDLIX + "\"" + "," + "oauth_version="
  + sendVersion + "," + "oauth_signature=";

我尝试构建基本参数:

  String token3 = "oauth_consumer_key=" + oauth_consumer_key + "," + 
  "&oauth_nonce=" + XXDLIX.trim() + ","  + "&oauth_signature_method=" + 
   signatureMethod + "," + "&oauth_timestamp=" + TimeStamp + ","  
   + "&oauth_token=" + oauth_request_token + "," + "&oauth_version=" + 
   Oauth_Version; 

构建密钥字符串(不确定这是正确的还是我 为此需要两个键。我的研究表明我 确实,所以尝试了):

   keyString = consumerSecretStr + "&" + accessSecretStr + "&";
   keyString = URLEncoder.encode(keyString.trim(), ENC);

并使用:

   url2 = URLEncoder.encode(url1.trim(), ENC);
   oauth_signature = "";
   oauth_signature = getSignature(url2, token3);
   oauth_signature = URLEncoder.encode(oauth_signature.trim(), ENC);

   public static String getSignature(String url, String params)
         throws UnsupportedEncodingException, NoSuchAlgorithmException,
         InvalidKeyException {

      StringBuilder base = new StringBuilder();
      base.append("GET&");
      base.append(url);
      base.append("&");
      base.append(params);

      byte[] keyBytes = (keyString.getBytes(ENC));

      SecretKey key = new SecretKeySpec(keyBytes, "HmacSHA1");

      Mac mac = Mac.getInstance("HmacSHA1");
      mac.init(key);

      return new String(Base64.getEncoder().encode
                    (mac.doFinal(base.toString().getBytes(
                    ENC))), ENC).trim();
   } 

请参阅上面的令牌字符串:

       String token = token + "\"" + oauth_signature + "\"" + "\"";

最后,我尝试使用此方法创建OAuth签名:

     ArrayList<String> params = new ArrayList<String>();
        params.add("oauth_consumer_key=" + oauth_consumer_key);
        params.add("oauth_token=" + oauth_request_token);
        params.add("oauth_signature_method=" + signatureMethod);
        params.add("oauth_timestamp=" + TimeStamp);
        params.add("oauth_nonce=" + XXDLIX.trim());
        params.add("oauth_version=" + Oauth_Version);
        Collections.sort(params); 
        //I was told they had to be in Alphabetical Order
       StringBuffer parametersList = new StringBuffer();
   for ( int i = 0; i < params.size(); i++ ){
       parametersList.append( ( ( i > 0 ) ? "&" : "" ) + params.get( i ));
   }
       String token2 = URLEncoder.encode(parametersList.toString(), ENC);
   String signatureString = GetMethod + "&" + 
          URLEncoder.encode(("https://my url" + "&"), ENC) + 
          (URLEncoder.encode(parametersList.toString(), ENC));

       String signature = null;
       try{
      SecretKeySpec signingKey = new SecretKeySpec( 
                      (keyString.getBytes()), "HmacSHA1" );
       Mac mac = Mac.getInstance( "HmacSHA1" );
       mac.init( signingKey );
       byte[] rawHMAC = mac.doFinal( signatureString.getBytes() );
       signature = Base64.getEncoder().encodeToString(rawHMAC);
       }
       catch ( Exception e )
       {
       System.err.println( "Unable to append signature" );
           System.exit( 0 );
       {

请参见上方的令牌字符串:

      String token = token + "\"" + signature + "\"";

公共类POBWSPOST2 {

public void POSTRequest2(String Data) throws IOException {

    XXDLIX = Data.trim();
    boolean sendMagento = false;
    String inline = null;
    TimeStamp = ""; 
    TimeStamp = getTimestamp();
    url1 = "https://myURL.com/GetAPI:
    String param = "?Authorization=" + oauth_request_token;

    keyString = consumerSecretStr + "&" + accessSecretStr + "&";
    keyString = URLEncoder.encode(keyString.trim(), ENC);

    String jsontext = json_object.toString();
        try
        {
            String token = "\"" + "OAuth oauth_consumer_key=" + consumerKeyStr + "," 
                   + "oauth_token=" + accessTokenStr + "," + "oauth_signature_method=" + signatureMethod  
                   + "," + "oauth_timestamp=" + "\"" + TimeStamp + "\"" + "," + "oauth_nonce="
                   + "\"" + XXDLIX + "\"" + "," + "oauth_version=" + sendVersion + "," + "oauth_signature=";

            String token4 = "\"" + "OAuth realm ="  + "\"" + url1 +  "\"" + "," 
                    + "oauth_consumer_key=" + consumerKeyStr + "," 
                    + "oauth_token=" + accessTokenStr + "," + "oauth_signature_method=" + signatureMethod  
                    + "," + "oauth_timestamp=" + "\"" + TimeStamp + "\"" + "," + "oauth_nonce="
                    + "\"" + XXDLIX + "\"" + "," + "oauth_version=" + sendVersion + "," + "oauth_signature=";

            ArrayList<String> params = new ArrayList<String>();
            params.add("oauth_consumer_key=" + oauth_consumer_key);
            params.add("oauth_token=" + oauth_request_token);
            params.add("oauth_signature_method=" + signatureMethod);
            params.add("oauth_timestamp=" + TimeStamp);
            params.add("oauth_nonce=" + XXDLIX.trim());
            params.add("oauth_version=" + Oauth_Version);
            Collections.sort(params);
            StringBuffer parametersList = new StringBuffer();
            for ( int i = 0; i < params.size(); i++ )
            {
                parametersList.append( ( ( i > 0 ) ? "&" : "" ) + params.get( i ) );
            }
            String token2 = URLEncoder.encode(parametersList.toString(), ENC);
            String signatureString = 
                  GetMethod + "&" + URLEncoder.encode(("https://myUrl.com/myAPI + "&"), ENC) + (URLEncoder.encode(parametersList.toString(), ENC));

                String signature = null;

                try
                {
                  SecretKeySpec signingKey = new SecretKeySpec( 
                    (keyString.getBytes()), "HmacSHA1" );
                  Mac mac = Mac.getInstance( "HmacSHA1" );
                  mac.init( signingKey );
                  byte[] rawHMAC = mac.doFinal( signatureString.getBytes() );
                  signature = Base64.getEncoder().encodeToString(rawHMAC);
                }
                catch ( Exception e )
                {
                  System.err.println( "Unable to append signature" );
                  System.exit( 0 );
                }

                String token3 = "oauth_consumer_key=" + oauth_consumer_key + "," + "&oauth_nonce=" + XXDLIX.trim() + ","
                        + "&oauth_signature_method=" + signatureMethod + "," + "&oauth_timestamp=" + TimeStamp + ","  
                        + "&oauth_token=" + oauth_request_token + "," + "&oauth_version=" + Oauth_Version;    

            try{
                url2 = URLEncoder.encode(url1.trim(), ENC);
                signature = URLEncoder.encode(signature.trim(), ENC);
                oauth_signature = "";
                oauth_signature = getSignature(url2, token3);

                oauth_signature = URLEncoder.encode(oauth_signature.trim(), ENC);
                token = token + "\"" + signature + "\"";
                String token6 = token + "\"" + oauth_signature + "\"" + "\"";
                //token = token + "\"" + URLEncoder.encode(oauth_signature, ENC) + "\"" + "\"";
                url = new URL(url1);
                //token = token + OAuthsignature;
                //String responsive = GetRequest(token);
                //String responsive1 = GetRequest(token6);
            } catch (InvalidKeyException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            HttpURLConnection connn = (HttpURLConnection) url.openConnection();

            connn.setReadTimeout(10000);
            connn.setConnectTimeout(15000);
            connn.setRequestProperty("Authorization", token);
            connn.setRequestProperty("Content-Type", "application/json");
            connn.setRequestProperty("cache-control", "no-cache");
            connn.setDoOutput(true);
            connn.setRequestMethod("GET");

            connn.connect();
            int responseCode = connn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_CREATED) { //success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        connn.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                } in .close();
                // print result
                System.out.println(response.toString());
                sendMagento = true;
            } else {
                System.out.println("POST DID NOT WORK");
            }
            if(connn != null){
                connn.disconnect();
            }

        }
        catch (MalformedURLException e4)
        {
            e4.printStackTrace();
            sendMagento = false;
        } 
        catch (IOException e5)
        {
            e5.printStackTrace();
            sendMagento = false;
        }
}

public static String getSignature(String url, String params)
        throws UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeyException {

    StringBuilder base = new StringBuilder();
    base.append("GET&");
    base.append(url);
    base.append("&");
    base.append(params);

    byte[] keyBytes = (keyString.getBytes(ENC));

    SecretKey key = new SecretKeySpec(keyBytes, "HmacSHA1");

    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(key);

    return new String(Base64.getEncoder().encode(mac.doFinal(base.toString().getBytes(
           ENC))), ENC).trim();
}

0 个答案:

没有答案