OAuth introspection with dotNet

Introduction

This guide details how to get a dotNet core web API working with IBM Security Verify for validation of presented OAuth access tokens.

Instructions

  1. Create a new dotnet core web API (i.e. dotnet new webapi).
  2. Add the IdentityModel.AspNetCore.OAuth2Introspection library.
  3. Within Startups.cs add the following:
services.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme)
        .AddOAuth2Introspection(options =>
         {
             options.ClientId = "xxx-xxxx-xxxx-xxxxxx";
             options.ClientSecret = "xxxxxxx";
             options.IntrospectionEndpoint = "https://{{tenant_url}}/v1.0/endpoint/default/introspect"
            });
  1. If you want use scopes within your API. Define different policies, and assign them to the scopes you assign the API client in ISV. Below is an example of a Polcy named Read which is assigned if the bearer token has scope API:Read.
services.AddAuthorization(options => 
{
    options.AddPolicy("Read", policy => policy.RequireClaim("scope", "API:Read"));
});
  1. Within the Configure() method, add app.UseAuthentication(); and app.UseAuthorization();:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseMiddleware<MyMiddleware>();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
  1. On each endpoint you want to protect, add the [Authorize] tag, and specify the Policies you defined under Step 4. For example, if token as scope API:Read then it has policy Read which means it is authorised to use the endpoint defined below.
[HttpGet]
[Authorize(Policy = "Read")]
public ActionResult Get()
{
    return Ok();
}

Did this page help you?