Last active
August 29, 2015 14:09
-
-
Save nawada/b261a43d2e6150106747 to your computer and use it in GitHub Desktop.
Slim3とTwitter4JでTwitter認証
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AuthController extends Controller { | |
@Override | |
public Navigation run() throws Exception { | |
// コンシューマーキー、コンシューマーシークレットを設定 | |
// twitter4j.propertiesを使用する方法わからず… | |
final String consumerKey = CONSUMER_KEY; | |
final String consumerSecret = CONSUMER_SECRET; | |
// Twitterインスタンス生成 | |
ConfigurationBuilder cb = new ConfigurationBuilder(); | |
cb.setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret) | |
.setOAuthAccessToken(null).setOAuthAccessTokenSecret(null); | |
TwitterFactory tf = new TwitterFactory(cb.build()); | |
Twitter twitter = tf.getInstance(); | |
// コールバック用に保持 | |
sessionScope("twitter", twitter); | |
// コールバックURL取得 | |
StringBuffer callbackUrl = request.getRequestURL(); | |
int index = callbackUrl.lastIndexOf("/"); | |
callbackUrl.replace(index, callbackUrl.length(), "").append("/callback"); | |
try { | |
// リクエストトークン発行 | |
RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl.toString()); | |
// コールバック用に保持 | |
sessionScope("requestToken", requestToken); | |
// 認証URLへリダイレクト | |
// Controller.redirect()を使用するとリダイレクトループが発生する模様 | |
response.sendRedirect(requestToken.getAuthenticationURL()); | |
return null; | |
} catch (TwitterException e) { | |
throw new ServletException(e); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CallbackController extends Controller { | |
@Override | |
public Navigation run() throws Exception { | |
Twitter twitter = (Twitter) sessionScope("twitter"); | |
RequestToken requestToken = (RequestToken) sessionScope("requestToken"); | |
String verifier = asString("oauth_verifier"); | |
try { | |
twitter.getOAuthAccessToken(requestToken, verifier); | |
removeSessionScope("requestToken"); | |
} catch (TwitterException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment