I need to be able to pass an Okta Token from a stand alone .NET Client (non-UI) to a REST API that is available. I have used the examples I have found in the forums to attempt to get a token. When I run it, I get an HTTP response 400 - Bad Request. I haven’t been able to figure out this problem. Here is my code:
using (var client = new HttpClient())
{
var clientId = "{My Client ID}";
var clientSecret = "{My Client Secret}";
var tokenUrl = "https://myserver/oauth2/default/v1/token";
var clientCredentials = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", clientCredentials);
var postMessage = new Dictionary<string, string>()
{
{ "grant_type", "client_credentials" },
{ "scope", "access_token" }
};
var request = new HttpRequestMessage(HttpMethod.Post, tokenUrl)
{
Content = new FormUrlEncodedContent(postMessage)
};
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode) // Get 400 Response Code Here
{
var json = await response.Content.ReadAsStringAsync();
}
}
Are you getting a more descriptive error summary back when you receive the 400? There can be multiple causes for a 400 (for example, requesting a scope that doesn’t exist) and you should be receiving an error summary from our API with more information about what is causing the error.
Actually, I just saw the error message as follows: The refresh token is invalid or expired. Any ideas on how to correctly get the refresh token? I don’t have a previous token since this is the first call.
For Client Credentials flow there is no refresh_token. The below code is from Postman Code generation and shouldl work.
May try testing with Postman first to make sure all the parameters are set, then do something like the below,
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post,
"https://{domain}/oauth2/default/v1/token");
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Authorization", "Basic MG9...==");
var collection = new List<KeyValuePair<string, string>>();
collection.Add(new("grant_type", "client_credentials"));
collection.Add(new("scope", "{VALID_SCOPE_SET_IN_YOUR_AUTH_SERVER}"));
var content = new FormUrlEncodedContent(collection);
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
``