Call API from ASP.Net Core 2.0

Please forgive me for the novelty of this question or if it has been covered somewhere else; I’ve been looking all over for a working example but haven’t found anything. I’m a novice in both C#/ASP.NET Core 2.0 and the Okta platform.

I was able to set up a basic working solution where the user authenticates using the OpenID quickstart.

Now I’m trying to call the Okta API from the backend to get information about “me” as a logged in user. Eventually, I want to get groups and role information (i.e., is the visitor a super user or admin, etc.) but am trying to start simple.

Here is my controller

[Authorize]
public IActionResult ShowUser()
{
  using (HttpClient client = new HttpClient())
  {
    client.BaseAddress = new Uri("https://{{My Company}}.oktapreview.com");

    byte[] cred = UTF8Encoding.UTF8.GetBytes("{{My API Token}}");

    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
        "Bearer", Convert.ToBase64String(cred));

    HttpResponseMessage response = client.GetAsync("/api/v1/users/me").Result;
    string stringData = response.Content.ReadAsStringAsync().Result;

    // Just for demo purposes
    ViewData["Results"] = stringData;

    return View();
  }
}

The error I’m receiving is:

{
"errorCode":"E0000005",
"errorSummary":"Invalid session",
"errorLink":"E0000005",
"errorId":"oaeOrQDpIWDTRyihIThHokg4g",
"errorCauses":[]
}

Can anyone point me in the direction of what I’m doing wrong here?

If you look at the “get current session” API - Sessions | Okta Developer, you will notice the following -

This operation requires a session cookie for the user. API token is not allowed for this operation.

Make sure that your session cookie is set (user is logged in) and don’t pass the API Token in your code.

Here’s an older thread which might be helpful - OKTA Session Id Retrieval - Stack Overflow

Hey @bleonard! It sounds like you’ve been able to log a user in via OpenID Connect, but you want to get more info about them. At a high level, you have two options:

  • Look at the claims in the ClaimsIdentity. The claims in theID token returned from Okta (which is consumed by the ASP.NET Core OpenID Connect middleware) are automatically put into the ClaimsIdentity that represents the user. For example, you can do
var name = HttpContext.User.Claims.FirstOrDefault(x => x.Type == "name")
  • If you want more than the few claims that come through the ID token, you can use the Okta .NET SDK to easily call the Okta Users API. The user’s Okta ID is available via the sub claim. For example:
var user = await client.User.GetUserAsync("<user id>");

We recently updated the Okta + ASP.NET Core 2.0 example to demonstrate this, in case you want another example. :slight_smile:

Let me know if this is what you’re looking for!

@nate.barbettini This looks very promising, thanks for the update!

I do have one (probably dumb) question regarding the OrgUrl in appsettings.json. In the QuickStart the Org Url is said to be found “On the home screen of the developer dashboard, in the upper right.” I don’t see anything that looks like an Org Url when I look at https://{{MyCompany}}-admin.oktapreview.com/admin/dashboard. Am I looking in the wrong spot?

You might be in the admin console, you can switch over to the developer console using the picker in the top left .

Your Org URL should be the admin link without the -admin

if you are looking at the admin dashboard and your url is:

my-company-admin.oktapreview.com

your org url should be:

my-company.oktapreview.com

hope this helps!

I was FINALLY able to take another look at this and I’ve run into an interesting problem.

I’ve pulled an updated copy of the ASP.Net Core MVC example and have updated appsettings with my credentials.

Nothing fancy but unfortunately I’m receiving a 401 Unauthorized error.

An unhandled exception occurred while processing the request.
HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()

IOException: IDX10804: Unable to retrieve document from: 'https://{{my-company}}.oktapreview.com/oauth2/default/.well-known/openid-configuration'.
Microsoft.IdentityModel.Protocols.HttpDocumentRetriever+<GetDocumentAsync>d__8.MoveNext()

InvalidOperationException: IDX10803: Unable to obtain configuration from: 'https://{{my-company}}.oktapreview.com/oauth2/default/.well-known/openid-configuration'.
Microsoft.IdentityModel.Protocols.ConfigurationManager+<GetConfigurationAsync>d__24.MoveNext()

I’ve verified that the App in Okta exists and that the API Token is good. I’m kind of at a loss since I haven’t done anything outside of adding the respective values. Thoughts?

From the IDX10408 error, it appears that aspnetcore wasn’t able to communicate with your Okta domain. What happens when you try to open https://{{my-company}}.oktapreview.com/oauth2/default/.well-known/openid-configuration in a web browser?

You should see a JSON document like: https://nate-example.oktapreview.com/oauth2/default/.well-known/openid-configuration

If that’s not working, make sure {{my-company}} is correct. As Tom mentioned above, a common problem is including -admin in the URL (that is only used to access the web console).

Hi Nate - thanks for yours and Tom’s help.
When I check the URL in a browser I get

{
"errorCode": "E0000015",
"errorSummary": "You do not have permission to access the feature you are requesting",
"errorLink": "E0000015",
"errorId": "oaejhmcqeYATAykReV6Nz_yAg",
"errorCauses": []
}

So it looks like this feature is denied or turned off? How can I go about activating/enabling it?

The {{-admin}} thing sounds like it trips a lot of people up. I haven’t been including it in my string values as you and Tom have both reminded me not to.

@nate.barbettini, I am having this same issue if you know what is causing it.

@ehs_ziluckm The free developer tier of Okta includes the API Access Management product. In my case, my company’s implementation of Okta did not include access to API Access Management which resulted in the errors I was seeing and that prompted this original post.

Hope this helps.