今回はコードだらけの記事に。
TwitterのOAuth認証するJavaプログラムのコード。
Google App Engineなどでも使えます。サーブレッドなんで。
これは設定事項を任意に設定しておけば動作する(はず) 以下の画像の工程を最初から最後のデータ取得しクッキーに格納するところまで動作します。
http://cdn-ak.f.st-hatena.com/images/fotolife/y/yuroyoro/20100506/20100506190425_original.png
package com.appspot.axe1lyzelab;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.security.Key;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.crypto.*;
import javax.crypto.spec.*;
import com.google.appengine.repackaged.com.google.common.util.Base64;
import javax.servlet.http.*;
@SuppressWarnings(“serial”)
public class OauthLogin extends HttpServlet {
private HttpServletRequest req;
private HttpServletResponse resp;
private HttpSession session;
String responseText = “”;
static final String REQUSET_TOKEN_URL=”http://api.twitter.com/oauth/request_token”;
static final String AUTHORIZE_URL=”http://api.twitter.com/oauth/authorize”;
static final String ACCESS_TOKEN_URL=”http://api.twitter.com/oauth/access_token”;
static final String APPLICATION_URL = “/”;
static final String SELF_URL = “/oauth”;
static final String CONSUMER_KEY=”xxxxxxxxxxxx”;
static final String CONSUMER_SECRET=”xxxxxxxxxxxxx”;
static final String SIGNATURE_METHOD=”HmacSHA1″;
static final String VERSION = “1.0”;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{this.req=request;this.resp=response;session = req.getSession(true);
if(req.getParameterMap().isEmpty()){
session.invalidate();
session=req.getSession();
session.setAttribute(“oauth_token”,””);
session.setAttribute(“oauth_token_secret”,””);
session.setAttribute(“oauth_timestamp”,Long.toString(System.currentTimeMillis() / 1000));
session.setAttribute(“oauth_nonce”,Long.toString(System.nanoTime()));
try {getToken(REQUSET_TOKEN_URL);} catch (Exception e) {}
}else if(req.getParameter(“oauth_verifier”)!=null){
session.setAttribute(“oauth_verifier”,req.getParameter(“oauth_verifier”));
try {getToken(ACCESS_TOKEN_URL);} catch (Exception e) {}
Enumeration e = session.getAttributeNames();
while(e.hasMoreElements()) {
String key = (String)e.nextElement();
responseText+=key+” : “+(String) session.getAttribute(key)+”<BR><BR>”;
}responseText+=”<HR>”;
}else{
}
resp.setContentType(“text/html; charset=utf-8”);
resp.getWriter().write(“<html><head></head><body>”+responseText+”</body></html>”);
}
private void getToken(String from) throws MalformedURLException, IOException, NoSuchAlgorithmException, InvalidKeyException {
URLConnection url = new URL(from + “?” + getRequestParameters(from)).openConnection();
url.connect();
HashMap<String,String> parsedResponse = parseResponse(getResponse(new BufferedReader(new InputStreamReader(url.getInputStream()))));
if(from.equals(REQUSET_TOKEN_URL)){
session.setAttribute(“oauth_token_secret”,parsedResponse.get(“oauth_token_secret”));
resp.sendRedirect(AUTHORIZE_URL+”?oauth_token=”+parsedResponse.get(“oauth_token”));
}else if(from.equals(ACCESS_TOKEN_URL)){
Iterator entries = parsedResponse.entrySet().iterator();
while(entries.hasNext()){
Entry entry = (Entry) entries.next();
session.setAttribute((String)entry.getKey(),(String)entry.getValue());
}
}
}
private String getResponse(BufferedReader in) throws IOException{
String str = “”;
while (true) {
String line = in.readLine();
if (line == null) {break;}
str+=line;
}return str;
}
private String getRequestParameters(String URL) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, IllegalStateException {
String OauthData = “”;
OauthData += “oauth_consumer_key=” + CONSUMER_KEY;
OauthData += “&oauth_nonce=” + session.getAttribute(“oauth_nonce”);
OauthData += “&oauth_signature_method=HMAC-SHA1”;
OauthData += “&oauth_timestamp=” + session.getAttribute(“oauth_timestamp”);
OauthData += “&oauth_version=” + VERSION;
if(req.getParameter(“oauth_token”)!=null){OauthData += “&oauth_token=” + req.getParameter(“oauth_token”);}
if(!session.getAttribute(“oauth_token”).equals(“”)){OauthData += “&oauth_token=” + session.getAttribute(“oauth_token”);}
OauthData += “&oauth_signature=”+getSignature(getSignatureBaseString(URL,OauthData), getKeyString());
return OauthData;
}
private String getSignature(String signatureBaseString, String keyString)throws NoSuchAlgorithmException, InvalidKeyException,UnsupportedEncodingException, IllegalStateException {
Mac mac = Mac.getInstance(SIGNATURE_METHOD);
Key key = new SecretKeySpec(keyString.getBytes(),SIGNATURE_METHOD);
mac.init(key);
return URLEncoder.encode(Base64.encode(mac.doFinal(signatureBaseString.getBytes())),”UTF-8″);
}
private String getKeyString() {
if(session.getAttribute(“oauth_token_secret”).equals(“”)) {return CONSUMER_SECRET + “&”;
}else{return CONSUMER_SECRET + “&” + session.getAttribute(“oauth_token_secret”);}
}
private String getSignatureBaseString(String URL,String requestParameters)throws UnsupportedEncodingException {
return “GET&” + URLEncoder.encode(URL, “utf-8”) + “&”+ URLEncoder.encode(requestParameters, “utf-8”);
}
private HashMap<String,String> parseResponse(String response) {
HashMap<String,String> data = new HashMap<String,String>();
if (response.indexOf(“&”) != -1) {
String[] responseData = response.split(“&”);
for (int i = 0; i <= responseData.length-1; i++) {
String key = responseData[i].substring(0,responseData[i].indexOf(“=”));
String value = responseData[i].substring(responseData[i].indexOf(“=”)+1);
data.put(key, value);
}
}
return data;
}
}