So I have an application written in C#.
Trying to test Ghost Admin Api for retrieving tiers and I am getting a 403 forbidden error. However if I use postman/Httpie, with the same endpoint and token, I get a successful message:
Sample:
sing (var client = new HttpClient())
{
try
{
string url = “https://tobses-1.ghost.io/ghost/api/admin/tiers?include=monthly_price,yearly_price,benefits”;
client.DefaultRequestHeaders.Add("Authorization", $"Ghost {GenerateGhostToken("Ghost_Admin_Api_Key").Trim()}");
client.DefaultRequestHeaders.Add("Accept-Version", "v5.0");
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("GET Response:");
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
This is the generate ghost token I am using:
string GenerateGhostToken(string apiKey)
{
string[] keyParts = apiKey.Split(':');
string id = keyParts[0];
string secret = keyParts[1];
var securityKey = new SymmetricSecurityKey(HexStringToByteArray(secret));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var header = new JwtHeader(credentials)
{
{ "kid", id }
};
var payload = new JwtPayload
{
{ "aud", "/admin/" },
{ "exp", DateTimeOffset.UtcNow.ToUnixTimeSeconds() + 5 * 60 },
{ "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds() }
};
var jwtToken = new JwtSecurityToken(header, payload);
var tokenHandler = new JwtSecurityTokenHandler();
string token = tokenHandler.WriteToken(jwtToken);
Console.WriteLine("Generated Token: " + token);
return token;
}
And:
byte HexStringToByteArray(string hex)
{
int length = hex.Length;
byte bytes = new byte[length / 2];
for (int i = 0; i < length; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
for the admin api key, I created a custom integration in my admin settings >> integrations, and that is what I am using.
Full error response:
Response Status: Forbidden
Response: {“errors”:[{“message”:“Authorization failed”,“context”:“Unable to determine the authenticated user or integration. Check that cookies are being passed through if using session authentication.”,“type”:“NoPermissionError”,“details”:null,“property”:null,“help”:null,“code”:null,“id”:“895f75a0-d8f0-11ef-9264-55c001984736”,“ghostErrorCode”:null}]}
Any help here?