草庐IT

java - 使用带有 RSA-SHA1 的 Twitter joauth 验证 OAuth1a 签名请求?

coder 2023-08-29 原文

我有一个用例来验证 OAuth1 请求,该请求使用 RSA 私钥签名并在服务器端使用 RSA 公钥验证。

我从 Twitter 找到了这个库,它可以帮助我们验证/验证 Oauth 签名的请求。 https://github.com/twitter/joauth

我想利用这个库来验证来自 Jersey 或 Spring MVC 操作方法的请求。来自客户端的请求将使用私钥签名。最后,我将使用客户端的公钥来验证请求。这意味着 RSA-SHA1 算法。

Twitter joauth 似乎很有用,但我缺少将 HttpServletRequest 转换为 OAuthRequest 的代码

库自述文件建议将此作为工具,但我找不到执行 javax.servlet.http.HttpServletRequest 的代码 --> com.twitter.joauth.OAuthRequest 转换。

请求验证发生在具有以下签名的验证方法中。

public VerifierResult verify(UnpackedRequest.OAuth1Request request, String tokenSecret, String consumerSecret);

其次,我还想知道当验证方法采用 String 参数时,使用/读取 RSA 公钥与 twitter joauth 的最合适方法是什么?

最佳答案

我从未使用任何库通过 Twitter 对用户进行身份验证。但我刚刚查看了 UnpackedRequest.OAuth1Request。您可以通过填充所有参数来创建此类的实例。我已经编写了 Twitter OAuth Header creator,因此您可以只使用它来填充那些参数或直接发送 POST 请求而无需库。

这里有你需要的所有类(class):

签名 - 生成 OAuth 签名。

public class Signature {
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
    public static String calculateRFC2104HMAC(String data, String key)
            throws java.security.SignatureException
    {
        String result;
        try {
            SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
            Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(data.getBytes());
            result = new String(Base64.encodeBase64(rawHmac));
        } catch (Exception e) {
            throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
        }
        return result;
    }
}

NvpComparator - 对 header 中需要的参数进行排序。

public class NvpComparator implements Comparator<NameValuePair> {
    @Override
    public int compare(NameValuePair arg0, NameValuePair arg1) {
        String name0 = arg0.getName();
        String name1 = arg1.getName();
        return name0.compareTo(name1);
    }
}

OAuth - 用于 URL 编码。

class OAuth{
...
    public static String percentEncode(String s) {
            return URLEncoder.encode(s, "UTF-8")
                    .replace("+", "%20").replace("*", "%2A")
                    .replace("%7E", "~");
    }
...
}

HeaderCreator - 创建所有需要的参数并生成 OAuth header 参数。

public class HeaderCreator {
    private String authorization = "OAuth ";
    private String oAuthSignature;
    private String oAuthNonce;
    private String oAuthTimestamp;
    private String oAuthConsumerSecret;
    private String oAuthTokenSecret;

    public String getAuthorization() {
        return authorization;
    }

    public String getoAuthSignature() {
        return oAuthSignature;
    }

    public String getoAuthNonce() {
        return oAuthNonce;
    }

    public String getoAuthTimestamp() {
        return oAuthTimestamp;
    }

    public HeaderCreator(){}

    public HeaderCreator(String oAuthConsumerSecret){
        this.oAuthConsumerSecret = oAuthConsumerSecret;
    }

    public HeaderCreator(String oAuthConsumerSecret, String oAuthTokenSecret){
        this(oAuthConsumerSecret);
        this.oAuthTokenSecret = oAuthTokenSecret;
    }

    public String getTwitterServerTime() throws IOException, ParseException {
        HttpsURLConnection con = (HttpsURLConnection)
                new URL("https://api.twitter.com/oauth/request_token").openConnection();
        con.setRequestMethod("HEAD");
        con.getResponseCode();
        String twitterDate= con.getHeaderField("Date");
        DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
        Date date = formatter.parse(twitterDate);
        return String.valueOf(date.getTime() / 1000L);
    }

    public String generatedSignature(String url, String method, List<NameValuePair> allParams,
                                     boolean withToken) throws SignatureException {
        oAuthNonce = String.valueOf(System.currentTimeMillis());
        allParams.add(new BasicNameValuePair("oauth_nonce", oAuthNonce));
        try {
            oAuthTimestamp = getTwitterServerTime();
            allParams.add(new BasicNameValuePair("oauth_timestamp", oAuthTimestamp));
        }catch (Exception ex){
            //TODO: Log!!
        }

        Collections.sort(allParams, new NvpComparator());
        StringBuffer params = new StringBuffer();
        for(int i=0;i<allParams.size();i++)
        {
            NameValuePair nvp = allParams.get(i);
            if (i>0) {
                params.append("&");
            }
            params.append(nvp.getName() + "=" + OAuth.percentEncode(nvp.getValue()));
        }
        String signatureBaseStringTemplate = "%s&%s&%s";
        String signatureBaseString =  String.format(signatureBaseStringTemplate,
                OAuth.percentEncode(method),
                OAuth.percentEncode(url),
                OAuth.percentEncode(params.toString()));
        String compositeKey = OAuth.percentEncode(oAuthConsumerSecret)+"&";
        if(withToken) compositeKey+=OAuth.percentEncode(oAuthTokenSecret);
        oAuthSignature =  Signature.calculateRFC2104HMAC(signatureBaseString, compositeKey);

        return oAuthSignature;
    }

    public String generatedAuthorization(List<NameValuePair> allParams){
        authorization = "OAuth ";
        Collections.sort(allParams, new NvpComparator());
        for(NameValuePair nvm : allParams){
            authorization+=nvm.getName()+"="+OAuth.percentEncode(nvm.getValue())+", ";
        }
        authorization=authorization.substring(0,authorization.length()-2);
        return authorization;
    }

}

解释:
1. 获取推特服务器时间
在 oAuthTimestamp 中,您不需要服务器的时间,而是 Twitter 服务器的时间。如果你总是在某个 Twitter 服务器上发送请求,你可以优化它保存这个参数。

2. HeaderCreator.generatedSignature(...)
url - 推特 API 的逻辑 url
方法 - GET 或 POST。您必须始终使用“POST”
allParams - 您知道生成签名的参数 ("param_name", "param_value");
withToken - 如果你知道 oAuthTokenSecret 为真。否则为假。

3. HeaderCreator.generatedAuthorization(...)
在 generatedSignature(...) 之后使用此方法生成 OAuth header 字符串。
allParams - 它是您在 generatedSignature(...) 中使用的参数加上:nonce、签名、时间戳。始终使用:

allParams.add(new BasicNameValuePair("oauth_nonce", headerCreator.getoAuthNonce()));
allParams.add(new BasicNameValuePair("oauth_signature", headerCreator.getoAuthSignature()));
allParams.add(new BasicNameValuePair("oauth_timestamp", headerCreator.getoAuthTimestamp()));


现在您可以使用它在您的库中填充 UnpackedRequest.OAuth1Request
这里还有一个在没有库的情况下在 SpringMVC 中对用户进行身份验证的示例:
请求 - 发送帖子请求。

public class Requests {
    public static String sendPost(String url, String urlParameters, Map<String, String> prop) throws Exception {
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        con.setRequestMethod("POST");
        if(prop!=null) {
            for (Map.Entry<String, String> entry : prop.entrySet()) {
                con.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        BufferedReader in;
        if(responseCode==200) {
            in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
        }else{
            in = new BufferedReader(
                    new InputStreamReader(con.getErrorStream()));
        }
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }
}

twAuth(...) - 将其放入您的 Controller 中。当用户想要通过 Twitter 在您的站点中进行身份验证时执行它。

@RequestMapping(value = "/twauth", method = RequestMethod.GET)
    @ResponseBody
    public String twAuth(HttpServletResponse response) throws Exception{
        try {
            String url = "https://api.twitter.com/oauth/request_token";

            List<NameValuePair> allParams = new ArrayList<NameValuePair>();
            allParams.add(new BasicNameValuePair("oauth_callback", "http://127.0.0.1:8080/twlogin"));
            allParams.add(new BasicNameValuePair("oauth_consumer_key", "2YhNLyum1VY10UrWBMqBnatiT"));
            allParams.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1"));
            allParams.add(new BasicNameValuePair("oauth_version", "1.0"));

            HeaderCreator headerCreator = new HeaderCreator("RUesRE56vVWzN9VFcfA0jCBz9VkvkAmidXj8d1h2tS5EZDipSL");
            headerCreator.generatedSignature(url,"POST",allParams,false);
            allParams.add(new BasicNameValuePair("oauth_nonce", headerCreator.getoAuthNonce()));
            allParams.add(new BasicNameValuePair("oauth_signature", headerCreator.getoAuthSignature()));
            allParams.add(new BasicNameValuePair("oauth_timestamp", headerCreator.getoAuthTimestamp()));

            Map<String, String> props = new HashMap<String, String>();
            props.put("Authorization", headerCreator.generatedAuthorization(allParams));
            String twitterResponse = Requests.sendPost(url,"",props);
            Integer indOAuthToken = twitterResponse.indexOf("oauth_token");
            String oAuthToken = twitterResponse.substring(indOAuthToken, twitterResponse.indexOf("&",indOAuthToken));

            response.sendRedirect("https://api.twitter.com/oauth/authenticate?" + oAuthToken);
        }catch (Exception ex){
            //TODO: Log
            throw new Exception();
        }
        return "main";
    }

twLogin(...) - 将其放入您的 Controller 中。是推特的回调。

  @RequestMapping(value = "/twlogin", method = RequestMethod.GET)
    public String twLogin(@RequestParam("oauth_token") String oauthToken,
                          @RequestParam("oauth_verifier") String oauthVerifier,
                          Model model, HttpServletRequest request){
        try {
            if(oauthToken==null || oauthToken.equals("") ||
                    oauthVerifier==null || oauthVerifier.equals(""))
                return "main";

            String url = "https://api.twitter.com/oauth/access_token";

            List<NameValuePair> allParams = new ArrayList<NameValuePair>();
            allParams.add(new BasicNameValuePair("oauth_consumer_key", "2YhNLyum1VY10UrWBMqBnatiT"));
            allParams.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1"));
            allParams.add(new BasicNameValuePair("oauth_token", oauthToken));
            allParams.add(new BasicNameValuePair("oauth_version", "1.0"));
            NameValuePair oAuthVerifier = new BasicNameValuePair("oauth_verifier", oauthVerifier);
            allParams.add(oAuthVerifier);

            HeaderCreator headerCreator = new HeaderCreator("RUesRE56vVWzN9VFcfA0jCBz9VkvkAmidXj8d1h2tS5EZDipSL");
            headerCreator.generatedSignature(url,"POST",allParams,false);
            allParams.add(new BasicNameValuePair("oauth_nonce", headerCreator.getoAuthNonce()));
            allParams.add(new BasicNameValuePair("oauth_signature", headerCreator.getoAuthSignature()));
            allParams.add(new BasicNameValuePair("oauth_timestamp", headerCreator.getoAuthTimestamp()));
            allParams.remove(oAuthVerifier);

            Map<String, String> props = new HashMap<String, String>();
            props.put("Authorization", headerCreator.generatedAuthorization(allParams));

            String twitterResponse = Requests.sendPost(url,"oauth_verifier="+oauthVerifier,props);

            //Get user id

            Integer startIndexTmp = twitterResponse.indexOf("user_id")+8;
            Integer endIndexTmp = twitterResponse.indexOf("&",startIndexTmp);
            if(endIndexTmp<=0) endIndexTmp = twitterResponse.length()-1;
            Long userId = Long.parseLong(twitterResponse.substring(startIndexTmp, endIndexTmp));

            //Do what do you want...

        }catch (Exception ex){
            //TODO: Log
            throw new Exception();
        }
    }

关于java - 使用带有 RSA-SHA1 的 Twitter joauth 验证 OAuth1a 签名请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33054690/

有关java - 使用带有 RSA-SHA1 的 Twitter joauth 验证 OAuth1a 签名请求?的更多相关文章

  1. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  2. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

  3. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  4. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  5. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  6. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

  7. 【Java 面试合集】HashMap中为什么引入红黑树,而不是AVL树呢 - 2

    HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候

  8. 【Java入门】使用Java实现文件夹的遍历 - 2

    遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg

  9. java - 为什么 ruby​​ modulo 与 java/other lang 不同? - 2

    我基本上来自Java背景并且努力理解Ruby中的模运算。(5%3)(-5%3)(5%-3)(-5%-3)Java中的上述操作产生,2个-22个-2但在Ruby中,相同的表达式会产生21个-1-2.Ruby在逻辑上有多擅长这个?模块操作在Ruby中是如何实现的?如果将同一个操作定义为一个web服务,两个服务如何匹配逻辑。 最佳答案 在Java中,模运算的结果与被除数的符号相同。在Ruby中,它与除数的符号相同。remainder()在Ruby中与被除数的符号相同。您可能还想引用modulooperation.

  10. java - Ruby 相当于 Java 的 Collections.unmodifiableList 和 Collections.unmodifiableMap - 2

    Java的Collections.unmodifiableList和Collections.unmodifiableMap在Ruby标准API中是否有等价物? 最佳答案 使用freeze应用程序接口(interface):Preventsfurthermodificationstoobj.ARuntimeErrorwillberaisedifmodificationisattempted.Thereisnowaytounfreezeafrozenobject.SeealsoObject#frozen?.Thismethodretur

随机推荐