【问题标题】:Client Credentials Flows to Spotify API with Spring boot客户端凭证通过 Spring boot 流向 Spotify API
【发布时间】:2021-10-10 21:43:40
【问题描述】:

我刚刚开始学习Spring Boot。 我似乎无法正确获取对 Spotify 的 HTTP 请求。 我想通过客户端信用流向 Spotify API 发送带有给定参数的 POST。

我现在开始工作了,但这不是 Spring:

public static String sendAuthRequest() throws IOException, OAuthProblemException, OAuthSystemException {

    String client_id = "MY_ID";
    String client_secret = "MY_Secret";

    OAuthClientRequest clientReqAccessToken = OAuthClientRequest
            .tokenLocation("https://accounts.spotify.com/api/token")
            .setGrantType(GrantType.CLIENT_CREDENTIALS).setClientId(client_id).setClientSecret(client_secret)
            .buildBodyMessage();

    OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
    OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(clientReqAccessToken);

    return "Access Token: " + oAuthResponse.getAccessToken() + ", Expires in: " + oAuthResponse.getBody();
}

你们能帮我把它改成 Spring 吗? 我很想用 RestTemplate 尝试一下,但可以弄清楚如何正确添加参数。 Spotify 也需要它是 x-www-form-urlencoded

谢谢!

【问题讨论】:

  • 您的意思是创建一个 api post 请求吗?

标签: java spring spring-boot api spotify


【解决方案1】:

如果您打算创建一种机制来获取来自其他 API 服务的凭据,那么您可以先创建一个 spring 身份验证。可以看一些教程here或者basic here

之后,为客户端或用户创建实体并相应地设置身份验证(例如用户、用户详细信息)。然后有选择地考虑主体身份验证以使用其余控制器检索令牌(来自 Spotify)。例如,

@RestController
@RequestMapping("/api/token")
public class TokenController {
    
    @RequestMapping(method = RequestMethod.GET)
    public String getToken(@AuthenticationPrincipal UserDetail principal) {
        
        String client_id = principal.getId();
        String client_secret = principal.getSecret();

        OAuthClientRequest clientReqAccessToken = OAuthClientRequest
            .tokenLocation("https://accounts.spotify.com/api/token")
            .setGrantType(GrantType.CLIENT_CREDENTIALS).setClientId(client_id).setClientSecret(client_secret)
            .buildBodyMessage();

        OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
        OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(clientReqAccessToken);

        return "Access Token: " + oAuthResponse.getAccessToken() + ", Expires in: " + oAuthResponse.getBody();
    }
}

【讨论】:

  • 听起来不错!谢谢!
猜你喜欢
  • 2021-01-10
  • 2014-11-12
  • 2022-11-09
  • 2020-01-18
  • 1970-01-01
  • 2014-11-20
  • 2016-09-28
  • 2021-10-07
  • 2020-02-22
相关资源
最近更新 更多