如何在我的struts2应用程序中添加twitter功能

时间:2013-05-20 13:37:04

标签: struts2 twitter twitter-oauth

我开发了struts2 web应用程序,现在我希望人们从他们的Twitter帐户登录,所以我需要在我的正常登录按钮下放置一个名为“Login with Twitter”的按钮。我已经进行了Facebook集成,所以据我所知,我们需要首先在twitter中创建应用程序所以我这样做然后我很困惑该怎么做,请任何人指导我完成这些步骤。

1 个答案:

答案 0 :(得分:1)

我真的不记得使用Twitter注册您的应用程序的过程,但谷歌“使用Twitter进行单点登录(SSO)”。

首先,您需要注册您的应用程序,这样您将获得consumer_key和consumer_secret(不确定这些是否是twitters术语)。

然后,过程是使用这些凭据将用户发送到Twitter,让用户登录,然后通过回调将Twitter返回控制权返回给您的应用程序。该回调将包含授权令牌,该令牌将授予对twitter服务的访问权限,因此我们将在会话中保存该权限。

注册申请后,以下代码将执行登录,并让您发布字符串“hello!”到您的Twitter帐户(假设应用程序具有此权限)。

TwitterGrantAccess.java

package com.quaternion.demo.action.twitter;

import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.SessionAware;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.TwitterApi;
import org.scribe.model.Token;
import org.scribe.oauth.OAuthService;

@Results(value = {
    @Result(name = "success", location = "${authorizationURL}", type = "redirect"),
    @Result(name = "error", location = "/WEB-INF/content/error.jsp")
})
public class TwitterGrantAccess extends ActionSupport implements SessionAware {

    private Map<String, Object> session;
    private String authorizationURL = null;

    @Override
    public String execute() {
        //Twitter twitter = new TwitterFactory().getInstance();
        String consumer_key = "NOT_PUTTING_MY_KEY_ON_STACK_OVERFLOW!";
        String consumer_secret = "NOT_PUTTING_MY_CONSUMER_SECRET_ON_STACK_OVERFLOW!";

        OAuthService twitterService = new ServiceBuilder()
                .provider(TwitterApi.class)
                .apiKey(consumer_key)
                .apiSecret(consumer_secret)
                .callback("http://localhost:8080/demo/twitter/twitter-callback")
                .build();
        Token requestToken = twitterService.getRequestToken();
        authorizationURL = twitterService.getAuthorizationUrl(requestToken);
        session.put("twitterService", twitterService);
        session.put("requestToken", requestToken);
        return SUCCESS;
    }

    public String getAuthorizationURL() {
        return this.authorizationURL;
    }

    @Override
    public void setSession(Map<String, Object> map) {
        this.session = map;
    }
}

Twitter调用的回调(你不会以用户身份调用的东西)...... 的 TwitterCallback.java

package com.quaternion.demo.action.twitter;



import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.SessionAware;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

@Results(value = {
    @Result(name = "success", location = "/WEB-INF/content/twitter/twitter-callback-success.jsp"),
    @Result(name = "error", location = "/WEB-INF/content/twitter/twitter-callback-error.jsp")
})
public class TwitterCallback extends ActionSupport implements SessionAware {

    private Map<String, Object> session;
    private String key;
    private String secret;
    //returned from twitter
    private String oauth_token;
    private String oauth_verifier;

    @Override
    public String execute() {
        if (session.containsKey("accessToken") && session.get("accessToken") != null) {
            return SUCCESS; //accessToken already exists!
        }
        Token requestToken = (Token) session.get("requestToken");
        if (objectToken == null) {
            super.addActionError("requestToken is null");
            return ERROR;
        }
        OAuthService twitterService = (OAuthService) session.get("twitterService");
        System.out.println(requestToken.toString());
        System.out.println(this.getOauth_verifier());
        //Token accessToken = twitter.getOAuthAccessToken(requestToken, this.getOauth_verifier());
        Token accessToken = twitterService.getAccessToken(requestToken, new Verifier(this.getOauth_verifier()));
        session.put("accessToken", accessToken);
        this.setKey(accessToken.getToken()); //just to see something happen
        this.setSecret(accessToken.getSecret());//just to see something happen
        return SUCCESS;
    }

    @Override
    public void setSession(Map<String, Object> map) {
        this.session = map;
    }

    /**
     * @return the key
     */
    public String getKey() {
        return key;
    }

    /**
     * @param key the key to set
     */
    public void setKey(String key) {
        this.key = key;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public String getOauth_token() {
        return oauth_token;
    }

    /**
     * @param oauth_token the oauth_token to set
     */
    public void setOauth_token(String oauth_token) {
        this.oauth_token = oauth_token;
    }

    public String getOauth_verifier() {
        return oauth_verifier;
    }


    public void setOauth_verifier(String oauth_verifier) {
        this.oauth_verifier = oauth_verifier;
    }
}

完成此操作后,您的应用程序现在可以使用API​​,让我们发布推文:

<强> Tweet.java

//Posts the string "hello!" to the users twitter feed then redirects to
//ken_mcwilliams twitter url, because that is the account I will be
//logging into... change you your own account during development 

package com.quaternion.demo.action.twitter;

import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.SessionAware;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;

@Results({
    @Result(name = "success", location = "https://twitter.com/#!/ken_mcwilliams", type = "redirect")
})
public class Tweet extends ActionSupport implements SessionAware {

    private Map<String, Object> session;
    private String status;

    @Override
    public String execute() {
        Token accessToken = (Token) session.get("accessToken");
        OAuthService twitterService = (OAuthService) session.get("twitterService");
        String url = "http://api.twitter.com/1/statuses/update.json?status=";
        String twitterStatus;
        if (status == null || status.isEmpty() == true) {
            twitterStatus = "hello!";
        }else{
            twitterStatus = status;
        }

        OAuthRequest request = new OAuthRequest(Verb.POST, url + twitterStatus);
        twitterService.signRequest(accessToken, request); // the access token from step 4
        Response response = request.send();
        return SUCCESS;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getStatus() {
        return this.status;
    }

    @Override
    public void setSession(Map<String, Object> map) {
        session = map;
    }
}

PS:twitter-callback-success.jsp和twitter-callback-error.jsp不包含任何有趣的内容,他们只是声明“你现在可以访问Twitter了,一切都很棒!”并且“出现了可怕的错误”。