I want to retrieve all the users from okta project using c# using machine to machine project. I mean using client id and secret. I have granted access to okta.users.read and created customScope named “access_token” it is able to retrieve token but “call 2” fails;
Also when i am giving the scope as okta.users.read “call 1” request fails.
static void RetrieveOktaUsers()
{
string BASE_URL = “”;
//
string CLIENT_ID = “clientid”;
string YOUR_CLIENT_SECRET = “secret”;
string OAUTH_ENDPOINT = "oauth2/default/v1/token";
string USERS_ENDPOINT = "api/v1/users";
string AUDIENCE = "";
OktaToken oktaToken = null;
//call 1
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(BASE_URL);
var authToken = Encoding.ASCII.GetBytes($"{CLIENT_ID}:{YOUR_CLIENT_SECRET}");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Basic”,
Convert.ToBase64String(authToken));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));
FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(new
{
new KeyValuePair<string, string>(“grant_type”, “client_credentials”),
new KeyValuePair<string, string>(“scope”, “access_token”),
new KeyValuePair<string, string>(“audience”, “api://default”),
});
HttpResponseMessage response = httpClient.PostAsync(OAUTH_ENDPOINT, formUrlEncodedContent).Result;
//response.EnsureSuccessStatusCode();
var resp = response.Content.ReadAsStringAsync().Result;
oktaToken = JsonConvert.DeserializeObject<OktaToken>(resp);
}
using (HttpClient httpClient = new HttpClient()) //Call 2
{
httpClient.BaseAddress = new Uri(BASE_URL);
httpClient.DefaultRequestHeaders.Add("authorization", $"Bearer {oktaToken.access_token}");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(USERS_ENDPOINT).Result;
//response.EnsureSuccessStatusCode();
var resp = response.Content.ReadAsStringAsync().Result;
}
}