通过 OAuth 访问社会网络 Web 站点,第 2 部分: 构建支持 OAuth 的 Web Twitter 客户端
2010-05-21 00:00:00 来源:WEB开发网doPost(...) 方法使用 login_twitter.html 和 update_twitter_status.jsp 处理 OAuth 身份验证和不同的交互。此应用程序的欢迎页面(login_twitter.html)提供了一个供用户登录 Twitter 的按钮,参见 图 1。当用户单击此按钮时,将会调用 doPost(...) 方法。有两种情况:新用户或返回的用户。如 清单 1 所示, 代码试图从 cookie 加载用户的 Twitter ID。如果没有加载 cookie,则用户将被视为新用户。将会从 Twitter 请求请求令牌,然后用户将被重定向到 Twitter,以授予代码读/写用户 Twitter 数据的权限,参见 图 2。如果一切都进行得很顺利,Twitter 应将用户重定向到在 web.xml 中设置的回调 URL。在这里我将回调 URL 设置为指向 servlet MyTtServlet。此次已授权了请求令牌并且它可以与 Twitter 交换以获得访问令牌。获得了访问令牌后,该访问令牌将会存储在 WEB-INF/token.txt 文件中以便将来使用。在实际应用中,您可能会在数据库中保存访问令牌。此外,cookie 将存储在用户的浏览器中,以便我们下次检查该用户是否是返回的用户。用户现在将被重定向到 update_twitter_status.jsp。成功登录页面如 图 3 所示,它显示了用户的上一次更新,以及其好友的一些时间轴。
清单 1. 使用 Twitter 进行 OAuth 身份验证
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
// Call back from Twitter
String oauthToken = request.getParameter(PARAM_OAUTH_TOKEN);
if (oauthToken != null) {
logger.debug(PARAM_OAUTH_TOKEN + " received from Twitter");
try {
Twitter twitter = (Twitter) session.getAttribute(ATTR_TWITTER);
RequestToken requestToken = (RequestToken) session
.getAttribute(ATTR_REQUEST_TOKEN);
AccessToken accessToken;
if (callbackUrl == null) {
accessToken = twitter.getOAuthAccessToken(requestToken);
} else {
String oauthVerifier = request
.getParameter(PARAM_OAUTH_VERIFIER);
logger.debug(PARAM_OAUTH_VERIFIER
+ " received from Twitter");
accessToken = twitter.getOAuthAccessToken(requestToken
.getToken(), requestToken.getTokenSecret(),
oauthVerifier);
}
twitter.setOAuthAccessToken(accessToken);
session.removeAttribute(ATTR_REQUEST_TOKEN);
session.setAttribute(ATTR_TWITTER, twitter);
int id = twitter.verifyCredentials().getId();
logger.debug("Access token retrieved for user " + id
+ " from Twitter");
storeAccessToken(id, accessToken);
Cookie cookie = new Cookie(COOKIE_TWITTER_ID, "" + id);
cookie.setMaxAge(63072000); // Valid for 2 years
response.addCookie(cookie);
logger.debug("Cookie set for user " + id);
// Get last status and friends' timelines
getMyLastStatusAndStoreInSession(session);
getFriendsTimelinesAndStoreInSession(session);
// Go to the update status page
request.getRequestDispatcher(PAGE_UPDATE_STATUS).forward(
request, response);
} catch (TwitterException e) {
logger.error("Failed to retrieve access token - "
+ e.getMessage());
throw new ServletException(e);
}
}
// Actions within this application
String action = request.getParameter(PARAM_ACTION);
if (ACTION_SIGN_IN.equals(action)) {
logger.debug("Signing in with Twitter...");
Twitter twitter = new Twitter();
twitter.setOAuthConsumer(consumerKey, consumerSecret);
// Try to load Twitter ID from cookies
String id = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
Cookie cookie;
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
if (COOKIE_TWITTER_ID.equals(cookie.getName())) {
id = cookie.getValue();
}
}
}
// Try to load access token if user's Twitter ID is retrieved
AccessToken accessToken = null;
if (id != null) {
accessToken = loadAccessToken(id);
if (accessToken != null) {
twitter.setOAuthAccessToken(accessToken);
session.setAttribute(ATTR_TWITTER, twitter);
// Get last status and friends' timelines
try {
getMyLastStatusAndStoreInSession(session);
getFriendsTimelinesAndStoreInSession(
session, true);
} catch (TwitterException e) {
e.printStackTrace();
}
// Access token loaded, go the up update status page
logger.debug("Going to the status update page...");
request.getRequestDispatcher(PAGE_UPDATE_STATUS).forward(
request, response);
}
}
// Can not load access token, go to Twitter for authentication
if (accessToken == null) {
try {
RequestToken requestToken;
if (callbackUrl == null) {
requestToken = twitter.getOAuthRequestToken();
} else {
requestToken =
twitter.getOAuthRequestToken(callbackUrl);
}
String authorisationUrl = requestToken
.getAuthorizationURL();
session.setAttribute(ATTR_TWITTER, twitter);
session.setAttribute(ATTR_REQUEST_TOKEN, requestToken);
logger.debug("Redirecting user to " + authorisationUrl);
response.sendRedirect(authorisationUrl);
} catch (TwitterException e) {
logger.error("Sign in with Twitter failed - "
+ e.getMessage());
throw new ServletException(e);
}
}
} else if (ACTION_UPDATE.equals(action)) {
// Handle ACTION_UPDATE, ACTION_DELETE, ACTION_MORE and ACTION_LATEST
......
}
更多精彩
赞助商链接