C# get access token and use refresh token

I’m using the following code snippet from the Okta site to get an access token. But getting a 400 Bad Request error. What could I be missing? I have verified the clientid, clientsecret and token url. Also the client credentials are enabled.

image

private async Task GetNewAccessToken()
{
var client = new HttpClient();
var clientId = _oktaSettings.Value.ClientId;
var clientSecret = _oktaSettings.Value.ClientSecret;
var clientCreds = System.Text.Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}");

		client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(clientCreds));

		var postMessage = new Dictionary<string, string>
		{
			{"grant_type", "client_credentials"},
			{"scope", "access_token"}
		};

		var request = new HttpRequestMessage(HttpMethod.Post, _oktaSettings.Value.TokenUrl)
		{
			Content = new FormUrlEncodedContent(postMessage)
		};

		var response = await client.SendAsync(request);
		if (response.IsSuccessStatusCode)
		{
			var json = await response.Content.ReadAsStringAsync();
			var newToken = JsonConvert.DeserializeObject<OktaToken>(json);
			newToken.ExpiresAt = DateTime.UtcNow.AddSeconds(_token.ExpiresIn);

			return newToken;
		}

		throw new ApplicationException("Unable to retrieve access token from Okta");
	}

Using post man gives this error

Bad request. Accept and/or Content-Type headers likely do not match supported values

When i use postman and use form-url-encoded, getting this error

{

"error": "invalid_client",

"error_description": "Client authentication failed. Either the client or the client credentials are invalid."

}

After some changes, using postman getting this error

One or more scopes are not configured for the authorization server resource

Found the issue. The scope was missing in the security - api.

Is there a guide/ code snippet on how to make use of the refresh token?

Currently, I’m checking if the token is valid and getting a new token using token endpoint when not. How do I add the code to the startup below in c#, so the refresh token will be automatically exchanged to get a new access token?

  services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddOktaMvc(new OktaMvcOptions
        {
            // Replace the Okta placeholders in appsettings.json with your Okta configuration.
            OktaDomain = config.GetValue<string>("Okta:OktaDomain"),
            ClientId = config.GetValue<string>("Okta:ClientId"),
            ClientSecret = config.GetValue<string>("Okta:ClientSecret"),
            AuthorizationServerId = config.GetValue<string>("Okta:AuthorizationServerId"),
            
        });
        services.Configure<OktaConfig>(config.GetSection("Okta"));

Are you still using Client Credentials flow? If so, you won’t be able to get a refresh token while using this flow and will need to just request a new access token when/if it expires.

We use authorization code flow. I turned on the client credentials as well only because we were getting an error because of the invalid access token after an hour and we did not know how to enable refresh code for a new access token automatically in c#.

Any help (sample code) would be greatly appreciated.

Solved. In case anyone is looking for a solution,

// Turn refresh_token on the okta site
// Add this to your startup code
.AddOktaMvc(new OktaMvcOptions
{
// Replace the Okta placeholders in appsettings.json with your Okta configuration.
OktaDomain = config.GetValue(“Okta:OktaDomain”),
ClientId = config.GetValue(“Okta:ClientId”),
ClientSecret = config.GetValue(“Okta:ClientSecret”),
AuthorizationServerId = config.GetValue(“Okta:AuthorizationServerId”),
Scope = new { “openid”, “offline_access” }
});

retrieve your refresh_token using

httpContext.GetTokenAsync(“refresh_token”)

// create a c# to simulate the
https://developer.okta.com/docs/guides/refresh-tokens/use-refresh-token/

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.