我需要将某些数据从一个请求传输到另一个请求以用于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";
}
来自frist请求的requestToken必须在下一个请求中可用。如何处理?
答案 0 :(得分:0)
嗯,一种方法是将它存储在“会话”中。我说放置引号,因为我不一定是指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。