使用spring社交推特获得401(需要授权)

时间:2014-12-24 22:41:19

标签: spring twitter spring-social

我一直在尝试Spring Social Accessing Twitter Data guide。虽然我已经翻了一倍,但是当我点击"连接到Twitter"按钮:

POST request for "https://api.twitter.com/oauth/request_token" resulted in 401 (Authorization Required); invoking error handler

这是我的代码:

src/main/resources/templates/connect/twitterConnect.html

<html>
<head>
    <title>Hello Twitter</title>
</head>
<body>
    <h3>Connect to Twitter</h3>

    <form action="/connect/twitter" method="POST">
        <div class="formInfo">
            <p>You aren't connected to Twitter yet. Click the button to connect this application with your Twitter account.</p>
        </div>
        <p><button type="submit">Connect to Twitter</button></p>
    </form>
</body>

src/main/resources/templates/connect/twitterConnected.html

<html>
<head>
    <title>Hello Twitter</title>
</head>
<body>
    <h3>Connected to Twitter</h3>

    <p>
        You are now connected to your Twitter account.
        Click <a href="/">here</a> to see your Twitter friends.
    </p>
</body>

src/main/resources/templates/hello.html

<html>
<head>
    <title>Hello Twitter</title>
</head>
<body>
    <h3>Hello, <span th:text="${twitterProfile.name}">Some User</span>!</h3>

    <h4>These are your friends:</h4>

    <ul>
        <li th:each="friend:${friends}" th:text="${friend.name}">Friend</li>
    </ul>
</body>

src/main/java/hello/HelloController.java

@Controller
@RequestMapping("/")
public class HelloController {

private Twitter twitter;

private ConnectionRepository connectionRepository;

@Inject
public HelloController(Twitter twitter, ConnectionRepository connectionRepository) {
    this.twitter = twitter;
    this.connectionRepository = connectionRepository;
}

@RequestMapping(method=RequestMethod.GET)
public String helloTwitter(Model model) {
    if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
        return "redirect:/connect/twitter";
    }

    model.addAttribute(twitter.userOperations().getUserProfile());
    CursoredList<TwitterProfile> friends = twitter.friendOperations().getFriends();
    model.addAttribute("friends", friends);
    return "hello";
}

}

src/main/java/hello/Application.java

 @Configuration
    @EnableAutoConfiguration
    @ComponentScan
    public class Application {

    /*
     * SPRING BOOTSTRAP MAIN
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    }

2 个答案:

答案 0 :(得分:17)

我遇到了同样的问题。

经过一番调查后,我发现问题出现在回调网址中。 Spring社交设置为yourap / signin / twitter。对于facebook和linkedin,这很好,但出于某种原因,twitter也会在应用程序设置中填写回调网址。

解决方案:转到您的Twitter应用程序设置,并填写回调网址(这甚至不必是您要使用的实际回调网址,只需填写任何网址!)。这很可能是造成问题的原因。

答案 1 :(得分:1)

您的application.properties文件是什么样的?它应该有spring.social.twitter.appId和spring.social.twitter.appSecret的条目,填充了在Twitter上注册应用程序时获得的值。

确保你在application.properties中有那些,并且值周围没有花括号(指南的文本显示大括号,但那些是占位符,而不是你应该在application.properties中实际拥有的东西) )。