1

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

4

1 回答 1

1

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

首先,您需要注册您的应用程序,在此过程中,您将获得一个 consumer_key 和一个 consumer_secret(不确定这些是否是 Twitter 术语)。

然后过程是使用这些凭据将用户发送到 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,让我们发布一条推文:

推文.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,一切都很棒!” 和“发生了可怕的错误”。

于 2013-05-20T19:14:33.460 回答