繁体   English   中英

使用Spring Social为Twitter和Facebook创建OAuth Flow

[英]Create OAuth Flow for Twitter and Facebook with spring social

对于oauth工作流程,我需要将某些数据从一个请求传输到另一个请求。

@RequestMapping(value = "/connect/twitter", method = RequestMethod.POST)
public RedirectView connectTwitter(HttpServletRequest request,
                                   Model model) {

    TwitterConnectionFactory connectionFactory = new TwitterConnectionFactory(
            environment.getProperty("spring.social.twitter.app-id"),
            environment.getProperty("spring.social.twitter.app-secret"));

    OAuth1Operations oauthOperations = connectionFactory.getOAuthOperations();
    OAuthToken requestToken = oauthOperations.fetchRequestToken(request.getRequestURL().toString(), null);
    String authorizeUrl = oauthOperations.buildAuthorizeUrl(requestToken.getValue(), OAuth1Parameters.NONE);

    //need requestToken in the next process

    return new RedirectView(authorizeUrl);
}

@RequestMapping(value = "/connect/twitter", method = RequestMethod.GET)
@ResponseBody
public String verifyTwitter(@RequestParam("oauth_token") String oauthToken,
                            @RequestParam("oauth_verifier") String oauthVerifier,
                            OAuthToken requestToken /*need requestToken from last request*/) {

    TwitterConnectionFactory connectionFactory = new TwitterConnectionFactory(
            environment.getProperty("spring.social.twitter.app-id"),
            environment.getProperty("spring.social.twitter.app-secret"));

    OAuth1Operations oauthOperations = connectionFactory.getOAuthOperations();
    OAuthToken accessToken = oauthOperations.exchangeForAccessToken(new AuthorizedRequestToken(requestToken, oauthVerifier), null);
    Connection<Twitter> twitterConnection = connectionFactory.createConnection(accessToken);

    return "asd";
}

来自第一个请求的requestToken必须在下一个请求中可用。 怎么处理呢?

好吧,一种实现方法是将其存储在“会话”中。 我之所以用引号引起来,是因为我不一定是指servlet会话(它可能会或可能不会在多个节点上工作,具体取决于您的服务器设置)。 它可以是执行会话功能的任何东西,例如(也许是)Redis键值存储。 当然,一旦您从“会话”中获取了它,您还将想要清除它。

为此,Spring MVC直接支持Flash属性。 参见http://docs.spring.io/spring/docs/4.0.6.RELEASE/spring-framework-reference/htmlsingle/#mvc-flash-attributes

同样,令我惊讶的是,您正在编写自己的控制器来与Twitter进行OAuth跳舞,但是为此目的已经存在Spring Social的ConnectController。 有关如何使用ConnectController的示例,请参见https://github.com/spring-projects/spring-social-samples/tree/master/spring-social-showcase

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM