Protecting a ASP.NET Core-based API is only a matter of configuring the JWT bearer authentication handler in DI, and adding the authentication middleware to the pipeline:

publicclassStartup{publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options=>{// base-address of your identityserveroptions.Authority="https://demo.identityserver.io";// name of the API resourceoptions.Audience="api1";});}publicvoidConfigure(IApplicationBuilderapp,ILoggerFactoryloggerFactory){app.UseAuthentication();app.UseMvc();}}

Our authentication handler serves the same purpose as the above handler
(in fact it uses the Microsoft JWT library internally), but adds a couple of additional features:

support for both JWTs and reference tokens

extensible caching for reference tokens

unified configuration model

scope validation

For the simplest case, our handler configuration looks very similar to the above snippet:

publicclassStartup{publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme).AddIdentityServerAuthentication(options=>{// base-address of your identityserveroptions.Authority="https://demo.identityserver.io";// name of the API resourceoptions.ApiName="api1";});}publicvoidConfigure(IApplicationBuilderapp,ILoggerFactoryloggerFactory){app.UseAuthentication();app.UseMvc();}}

If the incoming token is not a JWT, our middleware will contact the introspection endpoint found in the discovery document to validate the token.
Since the introspection endpoint requires authentication, you need to supply the configured API secret, e.g.:

.AddIdentityServerAuthentication(options=>{// base-address of your identityserveroptions.Authority="https://demo.identityserver.io";// name of the API resourceoptions.ApiName="api1";options.ApiSecret="secret";})

Typically, you don’t want to do a roundtrip to the introspection endpoint for each incoming request. The middleware has a built-in cache that you can enable like this:

.AddIdentityServerAuthentication(options=>{// base-address of your identityserveroptions.Authority="https://demo.identityserver.io";// name of the API resourceoptions.ApiName="api1";options.ApiSecret="secret";options.EnableCaching=true;options.CacheDuration=TimeSpan.FromMinutes(10);// that's the default})

The handler will use whatever IDistributedCache implementation is registered in the DI container (e.g. the standard MemoryDistributedCache).