OAuth 1.0 “无法验证您。”

huangapple go评论77阅读模式
英文:

OAuth 1.0 "Could not authenticate you."

问题

public String extendedtweet(String token, String secret,String id) throws IOException{

    String url = "https://api.twitter.com/1.1/statuses/lookup.json";
    headercreator hc = new headercreator(outhconsumerkey, consumersecret, token, secret);
    Map<String,String> requestparams = new HashMap<String, String>();
    Log.e("id", id);
    requestparams.put("id", id);
    // Add the "tweet_mode=extended" parameter
    requestparams.put("tweet_mode", "extended");
    String header = hc.generateHeader("GET", url, requestparams);
    Log.e("header", header);

    Response response = request(url, "", "GET", "Authorization", header);
    String jsonData = response.body().string();
    JsonObject js = new Gson().fromJson(jsonData, JsonObject.class);
    return js.get("full_text").getAsString();
}

The issue you're facing seems to be with authentication. The error message you're receiving, { "errors":[{"code":32,"message":"Could not authenticate you."}]}, indicates a problem with the authentication process. Make sure that your OAuth credentials (consumer key, consumer secret, token, and token secret) are correct and properly configured. Double-check that you're using the correct keys and secrets from your Twitter Developer account.

Additionally, ensure that your system's time is synchronized correctly, as OAuth 1.0a relies on timestamp and nonce values. If the timestamp is significantly different from Twitter's servers, it can cause authentication failures.

Since the problem seems to be authentication-related, please review your OAuth credentials and ensure that they are accurately implemented in your code.

英文:

Hı first of all this is a twitter auth. I can login, I can get the timeline etc etc. I can get those things because they dont want an extra paramaters. But now ı want to add "tweet_mode=extended" paramaters to that.

 public String extendedtweet(String token, String secret,String id) throws IOException{

    String url=&quot;https://api.twitter.com/1.1/statuses/lookup.json&quot;;
    headercreator hc=new headercreator(outhconsumerkey,consumersecret,token,secret);
    Map&lt;String,String&gt; requestparams = new HashMap&lt;String, String&gt;();
    Log.e(&quot;id&quot;,id);
    requestparams.put(&quot;id&quot;,id);
    String header=hc.generateHeader(&quot;GET&quot;,url,requestparams);
    Log.e(&quot;header&quot;,header);

    Response response =request(url,&quot;&quot;,&quot;GET&quot;,&quot;Authorization&quot;,header);
    String jsonData=response.body().string();
    JsonObject js=new Gson().fromJson(jsonData, JsonObject.class);
    return js.get(&quot;full_text&quot;).getAsString();


}

When ı Delete the

        requestparams.put(&quot;id&quot;,id);

Line at there it says id paramaters is missing.That is Nice because that shows me the problem is at the Headercreator class which is here :

   package com.example.twittertestvol1;

import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Class to generate Oauth 1.0a header for Twitter
 *
 */
@RequiresApi(api = Build.VERSION_CODES.N)
public class headercreator {

    private String consumerKey;
    private String consumerSecret;
    private String signatureMethod;
    private String token;
    private String tokenSecret;
    private String version;

    public headercreator(String consumerKey, String consumerSecret, String token, String tokenSecret) {
        this.consumerKey = consumerKey;
        this.consumerSecret = consumerSecret;
        this.token = token;
        this.tokenSecret = tokenSecret;
        this.signatureMethod = &quot;HMAC-SHA1&quot;;
        this.version = &quot;1.0&quot;;
    }

    private static final String oauth_consumer_key = &quot;oauth_consumer_key&quot;;
    private static final String oauth_token = &quot;oauth_token&quot;;
    private static final String oauth_signature_method = &quot;oauth_signature_method&quot;;
    private static final String oauth_timestamp = &quot;oauth_timestamp&quot;;
    private static final String oauth_nonce = &quot;oauth_nonce&quot;;
    private static final String oauth_version = &quot;oauth_version&quot;;
    private static final String oauth_signature = &quot;oauth_signature&quot;;
    private static final String HMAC_SHA1 = &quot;HmacSHA1&quot;;

    /**
     * Generates oAuth 1.0a header which can be pass as Authorization header
     *
     * @param httpMethod
     * @param url
     * @param requestParams
     * @return
     */
    public String generateHeader(String httpMethod, String url, Map&lt;String, String&gt; requestParams) {
        StringBuilder base = new StringBuilder();
        String nonce = getNonce();
        String timestamp = getTimestamp();
        String baseSignatureString = generateSignatureBaseString(httpMethod, url, requestParams, nonce, timestamp);
        String signature = encryptUsingHmacSHA1(baseSignatureString);
        base.append(&quot;OAuth &quot;);
        append(base, oauth_consumer_key, consumerKey);
        append(base, oauth_token, token);
        append(base, oauth_signature_method, signatureMethod);
        append(base, oauth_timestamp, timestamp);
        append(base, oauth_nonce, nonce);
        append(base, oauth_version, version);
        append(base, oauth_signature, signature);
        base.deleteCharAt(base.length() - 1);
        return base.toString();
    }

    /**
     * Generate base string to generate the oauth_signature
     *
     * @param httpMethod
     * @param url
     * @param requestParams
     * @return
     */
    private String generateSignatureBaseString(String httpMethod, String url, Map&lt;String, String&gt; requestParams, String nonce, String timestamp) {
        Map&lt;String, String&gt; params = new HashMap&lt;&gt;();
        if (requestParams!=null)
        {
            requestParams.entrySet().forEach(entry -&gt; {
                put(params, entry.getKey(), entry.getValue());
            });

        }
        put(params, oauth_consumer_key, consumerKey);
        put(params, oauth_nonce, nonce);
        put(params, oauth_signature_method, signatureMethod);
        put(params, oauth_timestamp, timestamp);
        put(params, oauth_token, token);
        put(params, oauth_version, version);
        Map&lt;String, String&gt; sortedParams = params.entrySet().stream().sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -&gt; oldValue, LinkedHashMap::new));
        StringBuilder base = new StringBuilder();
        sortedParams.entrySet().forEach(entry -&gt; {
            base.append(entry.getKey()).append(&quot;=&quot;).append(entry.getValue()).append(&quot;&amp;&quot;);
        });
        base.deleteCharAt(base.length() - 1);
        String baseString = httpMethod.toUpperCase() + &quot;&amp;&quot; + encode(url) + &quot;&amp;&quot; + encode(base.toString());
        return baseString;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private String encryptUsingHmacSHA1(String input) {
        String secret = new StringBuilder().append(encode(consumerSecret)).append(&quot;&amp;&quot;).append(encode(tokenSecret)).toString();
        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA1);
        Mac mac;
        try {
            mac = Mac.getInstance(HMAC_SHA1);
            mac.init(key);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
            return null;
        }
        byte[] signatureBytes = mac.doFinal(input.getBytes(StandardCharsets.UTF_8));
        return new String(Base64.getEncoder().encode(signatureBytes));
    }

    /**
     * Percentage encode String as per RFC 3986, Section 2.1
     *
     * @param value
     * @return
     */
    private String encode(String value) {
        String encoded = &quot;&quot;;
        try {
            encoded = URLEncoder.encode(value, &quot;UTF-8&quot;);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String sb = &quot;&quot;;
        char focus;
        for (int i = 0; i &lt; encoded.length(); i++) {
            focus = encoded.charAt(i);
            if (focus == &#39;*&#39;) {
                sb += &quot;%2A&quot;;
            } else if (focus == &#39;+&#39;) {
                sb += &quot;%20&quot;;
            } else if (focus == &#39;%&#39; &amp;&amp; i + 1 &lt; encoded.length() &amp;&amp; encoded.charAt(i + 1) == &#39;7&#39; &amp;&amp; encoded.charAt(i + 2) == &#39;E&#39;) {
                sb += &#39;~&#39;;
                i += 2;
            } else {
                sb += focus;
            }
        }
        return sb.toString();
    }

    private void put(Map&lt;String, String&gt; map, String key, String value) {
        map.put(encode(key), encode(value));
    }

    private void append(StringBuilder builder, String key, String value) {
        builder.append(encode(key)).append(&quot;=\&quot;&quot;).append(encode(value)).append(&quot;\&quot;,&quot;);
    }

    private String getNonce() {
        int leftLimit = 48; // numeral &#39;0&#39;
        int rightLimit = 122; // letter &#39;z&#39;
        int targetStringLength = 10;
        Random random = new Random();

        String generatedString = random.ints(leftLimit, rightLimit + 1).filter(i -&gt; (i &lt;= 57 || i &gt;= 65) &amp;&amp; (i &lt;= 90 || i &gt;= 97)).limit(targetStringLength)
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
        return generatedString;

    }

    private String getTimestamp() {
        return Math.round((new Date()).getTime() / 1000.0) + &quot;&quot;;
    }

}

Nowı wonder if someone shows me where is the problem why ı cant solve that. And that is the error code and error for that

> {"errors":[{"code":32,"message":"Could not authenticate you."}]}

Here is thre request function

private Response request(String url, String bodys, String type, String Headername, String Header) throws IOException {

    OkHttpClient client = new OkHttpClient();
    MediaType mediaType = MediaType.parse(&quot;text/plain&quot;);
    RequestBody body = RequestBody.create(mediaType,bodys);
    Request request;
    if (!Headername.equals(&quot;&quot;))
    {
        if (type.equals(&quot;GET&quot;))
        {

            request = new Request.Builder()
                    .url(url)
                    .method(type,null)
                    .addHeader(Headername,Header)
                    .build();

        }
        else{
            request = new Request.Builder()
                    .url(url)
                    .method(type, body)
                    .addHeader(Headername,Header)
                    .build();
        }

    }
    else {
        request = new Request.Builder()
                .url(url)
                .method(type, body)
                .build();

    }

    return client.newCall(request).execute();
}

答案1

得分: 1

问题出在Response response =request(url, "", "GET", "Authorization", header);

在调用服务时,您需要传递请求参数,但是在调用request()方法时没有传递id或任何其他参数。对我来说,以下代码有效:

public void getTweet() {
    Map<String, String> requestParams = new HashMap<>();
    String id = "1263213348000325633";
    // Pass all request params for header generation
    requestParams.put("id", id);
    requestParams.put("tweet_mode", "extended");
    String url = "https://api.twitter.com/1.1/statuses/lookup.json";
    String header = generator.generateHeader(HttpMethod.GET.name(), url, requestParams);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", header);
    HttpEntity<String> httpEntity = new HttpEntity<String>("body", headers);
    // Pass all request params in the request
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
            .queryParam("id", id)
            .queryParam("tweet_mode", "extended");
    ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
    String responseBody = response.getBody();
    assertNotNull(responseBody);
    System.out.println(responseBody);
}

可在此处找到可运行的代码链接,作为单元测试。

英文:

Issue is at Response response =request(url,&quot;&quot;,&quot;GET&quot;,&quot;Authorization&quot;,header);.

You need to pass in the request params when calling the service but you are not passing the id or any other param when calling the request() method. For me following code works:

    public void getTweet() {
        Map&lt;String, String&gt; requestParams = new HashMap&lt;&gt;();
        String id = &quot;1263213348000325633&quot;;
        // Pass all request params for header generation
        requestParams.put(&quot;id&quot;, id);
        requestParams.put(&quot;tweet_mode&quot;, &quot;extended&quot;);
        String url = &quot;https://api.twitter.com/1.1/statuses/lookup.json&quot;;
        String header = generator.generateHeader(HttpMethod.GET.name(), url, requestParams);
        HttpHeaders headers = new HttpHeaders();
        headers.add(&quot;Authorization&quot;, header);
        HttpEntity&lt;String&gt; httpEntity = new HttpEntity&lt;String&gt;(&quot;body&quot;, headers);
        // Pass all request params in the request
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam(&quot;id&quot;, id)
                .queryParam(&quot;tweet_mode&quot;, &quot;extended&quot;);
        ResponseEntity&lt;String&gt; response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
        String responseBody = response.getBody();
        assertNotNull(responseBody);
        System.out.println(responseBody);
    }

Working code available here as a junit.

huangapple
  • 本文由 发表于 2020年5月29日 07:52:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/62076397.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定