使用Twitter joauth和RSA-SHA1验证OAuth1a签名请求?

时间:2015-10-10 13:48:49

标签: java oauth cryptography rsa joauth

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

我在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);

其次我还想知道当verify方法接受String参数时,哪种方法最适合使用/读取带有twitter joauth的RSA公钥?

1 个答案:

答案 0 :(得分:1)

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

在这里所有课程你需要的:

签名 - 生成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 - 在标题中对您需要的参数进行排序。

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 - 用于网址编码。

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

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

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. getTwitterServerTime
在oAuthTimestamp中,您不需要服务器的时间,而是Twitter服务器的时间。如果您始终在某个Twitter服务器中发送请求,则可以优化它以保存此参数
2. HeaderCreator.generatedSignature(...)
url - 逻辑上url到twitter API
方法 - GET或POST。你必须始终使用&#34; POST&#34;
allParams - 您知道要生成签名的参数(&#34; param_name&#34;,&#34; param_value&#34;);
withToken - 如果你知道oAuthTokenSecret是真的。否则是假的
3. HeaderCreator.generatedAuthorization(...)
在generatedSignature(...)之后使用此方法生成OAuth标题字符串 allParams - 它是您在generatedSignature(...)中使用的参数加上: nonce,signature,timestamp 。始终使用:

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(...) - 将它放入您的控制器中。当用户想要通过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(...) - 将它放入您的控制器中。这是来自Twitter的回调。

  @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();
        }
    }