C# .NET Spotify API Access Token with Scopes Returns 401 Error

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?

The problem is you’re using the wrong OAuth flow. Client credentials flow doesn’t support user-specific scopes like user-read-private and user-read-email because it authenticates your application, not a specific user. That’s why you’re getting 401 when hitting /v1/me - there’s no user context. You need to implement the Authorization Code flow instead. This requires redirecting users to Spotify’s authorization page where they can grant permissions, then exchanging the returned authorization code for an access token. I ran into this exact issue last year when building a playlist manager. The client credentials flow is only meant for accessing public data that doesn’t require user permissions. For any endpoint that needs user data, you must go through the proper user authorization process first. Check Spotify’s documentation on the Authorization Code flow - it’s more complex but necessary for what you’re trying to achieve.

yep thats the issue right there - client credentials cant access user endpoints like /me because theres no actual user logged in. you need authorization code flow where the user goes to spotify and clicks allow. client credentials is just for app-only stuff like search or public playlists. basically spotify doesnt know which user you want data for so it blocks you.

I’ve encountered this exact authentication issue before and the root cause is definitely the OAuth flow mismatch. Your code is implementing client credentials flow which only grants application-level access, but you’re requesting user-specific scopes that require individual user consent. The Spotify API treats these as fundamentally different permission levels. When you use client credentials with user scopes, the API ignores those scopes entirely and gives you an app-only token, which explains why the me endpoint returns 401. You’ll need to switch to authorization code flow where users actually visit Spotify’s consent page and approve your app’s access to their data. This means implementing redirect URIs, handling authorization codes, and managing refresh tokens. It’s significantly more complex than your current implementation but absolutely required for accessing user profile endpoints. The token you’re getting now is valid but lacks the necessary user context that Spotify requires for personal data access.