How to Secure Your .NET Web API with Token Authentication

How to Secure Your .NET Web API with Token Authentication

With just a few lines of code, Okta can handle all the complicated and time-consuming security elements and let you concentrate on creating a stellar API.



is this a typo? OktaSettings is part of Okta.Core and I cannot find that package. I used ‘OktaClient’ and the error went away

message: 'The type or namespace name ‘OktaSettings’ could not be found (are you missing a using directive or an assembly

Edit: I wanted to try and build this myself but there’s too many of these in the posted code. I found Okta.Core but this.oktaSettings.Value.ClientId; generates an error as well. Please provide what you used to build this as well as what version of the SDK and Core you used. I am attempting to replicate it on VS Code on mac


OktaSettings is a class created earlier in the article:…

It packages up the ClientId, ClientSecret and TokenUrl into a custom object.

Hope this helps.


typed that at 1 in the morning. my eyes were failing me, sorry


No worries. I’ve been there. Thanks for keeping me honest! :slight_smile:

Adeem Rajpoot


Alex Brambila

I got this to compile but when i run the app I keep getting the error: Unable to retrieve access token from Okta.
when I look at the logs in okta it says no_matching_scope.
Any idea what the problem is?


You need to add scope to you appliaction.
API=>Authorization Servers => default (your app) => Scopes tab. Add access_token.

Vinay Pingale

this response helped me. thanks.
Can you add this information in main blog?

Marcus Marquardt

I built the example service and client with Net Core 2.1, but was unable to retrieve tokens from Okta even after adding the necessary custom scope to the auth server.

After much debugging, I discovered that adding an accept header to the OktaTokenService’s GetNewAccessToken() request allowed me to retrieve tokens.

Just in case anyone else has the same problem, here’s the line of code added to GetNewAccessToken(), along with the previous line of code for reference:

client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(“Basic”, System.Convert.ToBase64String(clientCreds));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));

Naveen Semwal

I have followed every step of it but i am getting error in GetNewAccessToken() as below :

StatusCode: 400, ReasonPhrase: ‘Bad Request’, Version: 1.1, Content: System.Net.Http.NoWriteNoSeekStreamContent, Headers:
Cache-Control: no-store, no-cache
Connection: close
Date: Thu, 30 Aug 2018 17:23:01 GMT
Pragma: no-cache
Transfer-Encoding: chunked
Server: nginx
Set-Cookie: sid=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/
Set-Cookie: JSESSIONID=CF56E23A70C3734774D5B904E6B290A7; Path=/; HttpOnly
Public-Key-Pins-Report-Only: pin-sha256=“jZomPEBSDXoipA9un78hKRIeN/+U4ZteRaiX8YpWfqc=”; pin-sha256=“axSbM6RQ+19oXxudaOTdwXJbSr6f7AahxbDHFy3p8s8=”; pin-sha256=“SE4qe2vdD9tAegPwO79rMnZyhHvqj3i5g1c2HkyGUNE=”; pin-sha256=“ylP0lMLMvBaiHn0ihLxHjzvlPVQNoyQ+rMiaj0da/Pw=”; max-age=60; report-uri=“…
X-Okta-Request-Id: W4gn9bDJypsxrjpfn6b1GAAABko
X-Rate-Limit-Limit: 10000
X-Rate-Limit-Remaining: 9999
X-Rate-Limit-Reset: 1535649841
Content-Type: application/json; charset=UTF-8
Expires: 0

Kelly J.

I was having this issue yesterday. Look at the comment below about adding scope, that seemed to get me past that point.

Kelly J.

Having an issue getting this demo to work. I believe I’ve followed everything correctly, but I get a status code of “Unauthorized” when I retrieve the Values. Currently banging my head against the wall on that.

On a lark, I tried navigating to “https://dev-502773.oktaprev…” in a browser, which is the URL that we are to put in the ConfigureServices() method in the API, and get a 404 error that way. Is that something expected or is something currently down?

Kelly J.

Thank you, this was very helpful


Ditto - looks to me like something is wrong in the writeup. My Okta logs (as shown on the dashboard) suggest that Okta is generating and returning valid tokens to my app, but for whatever reason my API is returning a 401/unauthorized when the tokens are sent to it. I noticed that the expiry timestamp coming in hadn’t applied my local daylight savings time, which led to incorrect ExpiresAt and IsValidAndNotExpiring values on my OktaToken objects. Correcting that unfortunately made no difference.


I think I fixed mine. Taking a hint from here […], I added:


…to the API application/Startup.cs/Configure method, before: app.UseMvc(); . I need to read up a little more to figure out what the hell it is I just did, but I’m getting results through at least. I think it’s something to do with using built in middleware versus rolling your own per this Stack thread: […].

Kelly J.

Adding the “app.UseAuthentication();” fixed it! Thank you very much!


Great article, almost exactly what I needed…

Is there a similar walkthrough that is for .NET Framework instead of .NET Core? There are some significant differences in the wiring up of services between the two frameworks, and I’m building a service in .NET Framework.

Stephen Mansfield

Hey, can you update the code text to .Net Core 2.2? Working with some newer Microsoft Azure products and must use Core 2.2. I tried to update your code to support 2.2 but there were too many components that did not work. Also I am new to .Net Core so I was even more handicapped. If at all possible a new update to your code to support .Net Core 2.2 would be great.


There is a post coming out very soon that will be about exactly that!