Issue Description
I’m having trouble with Spotify API authentication in my C# application. I can successfully get an access token, but when I try to use it with the /v1/me
endpoint, I keep getting a 401 error. The endpoint needs user-read-private
and user-read-email
permissions.
My Current Implementation
public async Task<SpotifyAuthResponse> RequestAccessTokenWithPermissions(SpotifyCredentials credentials, string[] permissions)
{
var permissionString = string.Join(" ", permissions);
var formData = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("scope", permissionString)
});
var credentialString = $"{credentials.AppId}:{credentials.AppSecret}";
var encodedCredentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentialString));
var httpRequest = new HttpRequestMessage(HttpMethod.Post, _authUrl)
{
Headers = { Authorization = new AuthenticationHeaderValue("Basic", encodedCredentials) },
Content = formData
};
var httpResponse = await _client.SendAsync(httpRequest);
if (!httpResponse.IsSuccessStatusCode)
{
var error = await httpResponse.Content.ReadAsStringAsync();
throw new Exception($"Authentication failed: {httpResponse.StatusCode} - {error}");
}
var responseJson = await httpResponse.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<SpotifyAuthResponse>(responseJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
Command Handler
public class SpotifyTokenRequest : IRequest<ApiResponse>
{
public string AppId { get; set; }
public string AppSecret { get; set; }
}
public class SpotifyTokenHandler : IRequestHandler<SpotifyTokenRequest, ApiResponse>
{
private readonly ISpotifyService _service;
public SpotifyTokenHandler(ISpotifyService service)
{
_service = service;
}
public async Task<ApiResponse> Handle(SpotifyTokenRequest command, CancellationToken token)
{
try
{
var credentials = new SpotifyCredentials
{
AppId = command.AppId,
AppSecret = command.AppSecret
};
var requiredPermissions = new[]
{
"user-read-private",
"user-read-email"
};
var authToken = await _service.RequestAccessTokenWithPermissions(credentials, requiredPermissions);
return new ApiResponse()
{
StatusCode = 200,
Message = "Token retrieved successfully",
Data = authToken
};
}
catch (Exception error)
{
return new ApiResponse()
{
StatusCode = 500,
Message = error.Message,
Data = null
};
}
}
}
The token generation works fine, but I can’t access user profile data. What am I missing here?