Spotify.NET/SpotifyAPI.Web/Authenticators/ClientCredentialsAuthenticator.cs

71 lines
2.6 KiB
C#
Raw Normal View History

2020-05-14 22:26:40 +01:00
using System.Threading.Tasks;
2020-06-03 16:44:13 +01:00
using SpotifyAPI.Web.Http;
2020-05-14 22:26:40 +01:00
2020-06-03 16:44:13 +01:00
namespace SpotifyAPI.Web
2020-05-14 22:26:40 +01:00
{
/// <summary>
/// This Authenticator requests new credentials token on demand and stores them into memory.
/// It is unable to query user specifc details.
/// </summary>
public class ClientCredentialsAuthenticator : IAuthenticator
2020-05-14 22:26:40 +01:00
{
/// <summary>
/// Initiate a new instance. The initial token will be fetched when the first API call occurs.
2020-05-14 22:26:40 +01:00
/// </summary>
/// <param name="clientId">
/// The ClientID, defined in a spotify application in your Spotify Developer Dashboard.
2020-05-14 22:26:40 +01:00
/// </param>
/// <param name="clientSecret">
/// The ClientSecret, defined in a spotify application in your Spotify Developer Dashboard.
2020-05-14 22:26:40 +01:00
/// </param>
public ClientCredentialsAuthenticator(string clientId, string clientSecret) : this(clientId, clientSecret, null) { }
/// <summary>
/// Initiate a new instance. The initial token is provided and will be used if not expired
/// </summary>
/// <param name="clientId">
/// The ClientID, defined in a spotify application in your Spotify Developer Dashboard.
/// </param>
/// <param name="clientSecret">
/// The ClientSecret, defined in a spotify application in your Spotify Developer Dashboard.
/// </param>
/// <param name="token">
/// An optional inital token received earlier.
/// </param>
public ClientCredentialsAuthenticator(string clientId, string clientSecret, ClientCredentialsTokenResponse? token)
2020-05-14 22:26:40 +01:00
{
Ensure.ArgumentNotNullOrEmptyString(clientId, nameof(clientId));
Ensure.ArgumentNotNullOrEmptyString(clientSecret, nameof(clientSecret));
ClientId = clientId;
ClientSecret = clientSecret;
Token = token;
2020-05-14 22:26:40 +01:00
}
public ClientCredentialsTokenResponse? Token { get; private set; }
2020-05-14 22:26:40 +01:00
/// <summary>
/// The ClientID, defined in a spotify application in your Spotify Developer Dashboard
/// </summary>
public string ClientId { get; }
/// <summary>
/// The ClientID, defined in a spotify application in your Spotify Developer Dashboard
/// </summary>
2020-05-15 19:06:24 +01:00
public string ClientSecret { get; }
2020-05-14 22:26:40 +01:00
public async Task Apply(IRequest request, IAPIConnector apiConnector)
{
Ensure.ArgumentNotNull(request, nameof(request));
if (Token == null || Token.IsExpired)
2020-05-14 22:26:40 +01:00
{
var tokenRequest = new ClientCredentialsRequest(ClientId, ClientSecret);
Token = await OAuthClient.RequestToken(tokenRequest, apiConnector).ConfigureAwait(false);
2020-05-14 22:26:40 +01:00
}
request.Headers["Authorization"] = $"{Token.TokenType} {Token.AccessToken}";
2020-05-14 22:26:40 +01:00
}
}
}