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

Ske*_*eve 5 twitter spring spring-social

我一直在尝试这个Spring社交访问Twitter数据指南.虽然我已经加倍,三倍,所以当我点击"连接到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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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";
}

}
Run Code Online (Sandbox Code Playgroud)

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);
    }

    }
Run Code Online (Sandbox Code Playgroud)

San*_*ola 17

我遇到了同样的问题.

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

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