在springboot上设置(oauth令牌)授权头

pw136qt2  于 2021-07-15  发布在  Java
关注(0)|答案(2)|浏览(450)

我必须发送get请求以请求具有以下标头的令牌url:

Content-Type: application/x-www-form-urlencoded
Authorization:
        OAuth oauth_consumer_key="your_consumer_key",
        oauth_nonce="random_string_or_timestamp",
        oauth_signature="your_consumer_secret&",
        oauth_signature_method="PLAINTEXT",
        oauth_timestamp="current_timestamp",
        oauth_callback="your_callback"
User-Agent: some_user_agent

我试过这段代码:

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("GET");

        conn.setRequestProperty("Authorization: OAuth oauth_consumer_key", "BaeUqWMTmCxjeJj9mkJr");
        conn.setRequestProperty("Authorization: oauth_nonce", "random_string_or_timestamp");
        conn.setRequestProperty("Authorization: oauth_signature", "ZWglyBtJasnJBqVndzyduYJggCduKeYks&");
        conn.setRequestProperty("Authorization: oauth_timestamp", String.valueOf(new Date()));
        conn.setRequestProperty("Authorization: oauth_callback", "http://localhost:8080");
        conn.setRequestProperty("User-Agent", "test");

        int statusCode = conn.getResponseCode();
        System.out.println("Response from WA Gateway: \n");
        System.out.println("Status Code: " + statusCode);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (statusCode == 200) ? conn.getInputStream() : conn.getErrorStream()
        ));
        String output;
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }
        conn.disconnect();

但我有个错误:

Illegal character(s) in message header field: Authorization: OAuth oauth_consumer_key
inb24sb2

inb24sb21#

问题是您没有正确地生成请求。因为这是一个 GET oauth请求的一个版本,下面是rfc5849中的一个示例
get/example/path?oauth\u consumer\u key=0685bd9184jfhq22&oauth\u token=ad180jjd733klru7&oauth\u signature\u method=hm ac-sha1&oauth\u signature=wojio9a2w5mfwdgidvzbtsmk%2fpy%3d&oauth\u timestamp=137131200&oauth\u nonce=4572616e48616d6d6d6d6d6d65724c61686176&oauth\u version=1.0 http/1.1
sp,设置 Authorization 中的标题 setRequestProperty 按照上述格式:

...
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String yourUrl = "http://yourwebsite.com";
String currentSeconds = 1618496867; // current seconds
String authorizationValue = "OAuth oauth_consumer_key=\"BaeUqWMTmCxjeJj9mkJr\",
    oauth_nonce=\"1618496867\",
    oauth_signature=\"ZWglyBtJasnJBqVndzyduYJggCduKeYks&\",
    oauth_signature_method=\"PLAINTEXT\",
    oauth_timestamp=\"1618496867\",
    oauth_callback=\"http://localhost:8080\""

conn.setRequestProperty("Authorization", authorizationValue);
conn.setDoOutput(true);
conn.setRequestMethod("GET");
...

我在oauth身份验证服务器上使用postman客户机测试了一个类似的请求,效果非常好。

tzdcorbm

tzdcorbm2#

这些不是标题,你必须计算它。。这样地
https://twittercommunity.com/t/solved-java-oauth-request-token-flow-example-without-libraries/1440

相关问题