Protect an API
To protect an API, you must have configured an API.
To secure the API, configure it to require an access token:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.Authority = authority; //Base URL to Idp
options.Audience = apiResource;
options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
options.TokenValidationParameters.NameClaimType = JwtClaimTypes.Name;
options.TokenValidationParameters.RoleClaimType = JwtClaimTypes.Role;
// if token does not contain a dot, it is a reference token
options.ForwardDefaultSelector = Selector.ForwardReferenceToken("introspection");
})
// reference tokens
.AddOAuth2Introspection("introspection", options =>
{
options.Authority = authority;
options.ClientId = apiResource;
options.ClientSecret = apiSecret;
options.EnableCaching = true;
options.CacheDuration = TimeSpan.FromMinutes(20);
options.NameClaimType = JwtClaimTypes.Name;
options.RoleClaimType = JwtClaimTypes.Role;
});
We have used the IdentityModel.AspNetCore.OAuth2Introspection NuGet package. Read more about ForwardDefaultSelector.
If you have API and web application in the same project, cookies are likely the default scheme used for authenticating requests. However, if you need to make pure API calls from, for example, a server application, you may encounter 401 errors. To address this, you can add a ForwardDefaultSelector to your Cookies configuration. This can be configured to check if the Authorization header starts with “Bearer” and, if so, set “Bearer” as the scheme to be used.
In IRM.AspNetCore.Authentication, there are ready-made extension methods to perform the typical configuration mentioned above.