Getting 401 Error When Accessing Spotify User Data with Generated Token
I’m working on a C# application that connects to Spotify’s API. I can successfully generate an access token, but when I try to use it to fetch user profile information, I get a 401 unauthorized error.
The issue happens specifically when I try to access user data that requires special permissions like reading private profile info and email addresses. My token generation seems to work fine, but something is wrong with how I’m handling the user permissions.
Here’s my token generation method:
public async Task<SpotifyAuthResponse> GenerateAccessTokenWithPermissions(SpotifyCredentials credentials, string[] permissions)
{
var permissionsList = string.Join(" ", permissions);
var formData = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("scope", permissionsList)
});
var credentialsData = $"{credentials.AppId}:{credentials.AppSecret}";
var encodedCredentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentialsData));
var httpRequest = new HttpRequestMessage(HttpMethod.Post, _apiTokenUrl)
{
Headers = { Authorization = new AuthenticationHeaderValue("Basic", encodedCredentials) },
Content = formData
};
var apiResponse = await _client.SendAsync(httpRequest);
if (!apiResponse.IsSuccessStatusCode)
{
var errorContent = await apiResponse.Content.ReadAsStringAsync();
throw new Exception($"API call failed: {apiResponse.StatusCode} - {errorContent}");
}
var responseContent = await apiResponse.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<SpotifyAuthResponse>(responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
And here’s my command handler that uses it:
public class RequestSpotifyUserToken : IRequest<ApiResponseDto>
{
public string AppId { get; set; }
public string AppSecret { get; set; }
}
public class RequestSpotifyUserTokenHandler : IRequestHandler<RequestSpotifyUserToken, ApiResponseDto>
{
private readonly ISpotifyService _spotifyService;
public RequestSpotifyUserTokenHandler(ISpotifyService spotifyService)
{
_spotifyService = spotifyService;
}
public async Task<ApiResponseDto> Handle(RequestSpotifyUserToken command, CancellationToken token)
{
try
{
var appCredentials = new SpotifyCredentials
{
AppId = command.AppId,
AppSecret = command.AppSecret
};
var requiredPermissions = new[]
{
"user-read-private",
"user-read-email"
};
Console.WriteLine($"Requesting access with permissions: {string.Join(", ", requiredPermissions)}");
var authToken = await _spotifyService.GenerateAccessTokenWithPermissions(appCredentials, requiredPermissions);
return new ApiResponseDto()
{
StatusCode = (int)HttpStatusCode.OK,
Message = "Authentication token created successfully.",
Data = authToken
};
}
catch (Exception error)
{
return new ApiResponseDto()
{
StatusCode = (int)HttpStatusCode.InternalServerError,
Message = error.Message,
Data = null
};
}
}
}
The token gets created without errors, but when I try to call the user profile endpoint with it, I get rejected. What am I missing here?