如何通过Spring控制器检索的Spotify访问令牌?

时间:2017-03-09 15:27:24

标签: java spring api spotify

我使用Spotify网络API来访问用户数据:

public class Application {
 public static void main(String[] args) throws Exception {  

    SpringApplication.run(Application.class, args);

    final String clientId = "clientId";
    final String clientSecret = "clientSecret";
    final String redirectURI = "http://localhost:8080/callback/";


    final Api api = Api.builder()
      .clientId(clientId)
      .clientSecret(clientSecret)
      .redirectURI(redirectURI)
      .build();

    /* Set the necessary scopes that the application will need from the user */
    final List<String> scopes = Arrays.asList("user-read-private", "user-read-email");

    /* Set a state. This is used to prevent cross site request forgeries. */
    final String state = "someExpectedStateString";

    String authorizeURL = api.createAuthorizeURL(scopes, state);
    /* Here connecting to authorizeURL */   
 }
}

然后我连接到authorizeUrl并从redirectUri获取访问令牌(代码),如下所示: localhost:8080 / callback /?code = 123

我可以在我的localhost中使用Spring控制器获取代码并显示它:

@RestController
public class TokenController {
  private static final String template = "Your Spotify acces code: %s";

  @RequestMapping("/callback/")
  public Token tokenValue(@RequestParam(value="code",  defaultValue="Spotify access code") String value) {
    return new Token(String.format(template, value));
  }
}

如何将此代码传递回我的应用程序,以便我可以完成授权过程?

1 个答案:

答案 0 :(得分:0)

我最初将它存储在http服务器中,然后通过另一种API方法从我的应用程序中查询http服务器。非常笨重且可能不安全。

后来的解决方案是在我的应用程序中嵌入一些轻量级的http服务器类。这让我只需阅读一些类变量。它需要相当多的集成,但解决方案非常干净。对于一个值来说似乎有很多代码。

我仍然对此不满意,但现在也会这样做。