簡體   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