Home > Software engineering >  Client Credentials Flows to Spotify API with Spring boot
Client Credentials Flows to Spotify API with Spring boot

Time:10-12

I'm junior just starting out and am trying to learn Spring boot. I can't seem to get my HTTP request to Spotify right. I want to send a POST with the given parameters to the Spotify API via Client Creditental Flows.

I got this working now, but this isn't 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();
}

Can you guys help me changing this into Spring ? I'd love to try it with RestTemplate but can to figure out how to add the parameters corretly. Also Spotify needs it to be x-www-form-urlencoded

Thank you!

CodePudding user response:

If you intend to create a mechanism for having credentials from other API services, then you can create a spring authentication first. You can see some tutorials here or a basic here

After so, create entities for the clients or users and set up the authentication accordingly (e.g. User, UserDetail). Then selectively consider the principal authentication to retrieve the token (in this from Spotify) using the rest controller. For example,

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

  • Related