After installing the package, you'll need to tell your API to use this scheme in the Startup.cs
file. The simplest way is using the extension method provided with the package:
public void ConfigureServices(IServiceCollection services)
{
// ...
// If only a single bot is authorized
services.UseBotAuthentication("bot authorization key");
// If multiple bots
services.UseBotAuthentication(authorizationKeyEnumerable); // pass any enumerable containing your keys
// ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseHttpsRedirection()
.UseAuthentication() // this is the line that should be added, and it MUST be before .UseRouting()
.UseRouting()
// ...
}
Once your API is configured to use it, you can enable it on a controller like so:
[Route("api/[controller]")]
[ApiController]
[Authorize] // add this to protect the whole controller
public class HealthController : ControllerBase
{
}
To protect only a given method:
[Route("api/[controller]")]
[ApiController]
public class HealthController : ControllerBase
{
[HttpGet, Authorize] // add the Authorize attribute here instead, to protect only the action
public IActionResult HealthCheck() {}
}
To exclude a given method from a protected controller:
[Route("api/[controller]")]
[ApiController, Authorize] // add the attribute
public class HealthController : ControllerBase
{
[HttpGet, AllowAnonymous] // Methods with AllowAnonymous will ignore the auth check
public IActionResult HealthCheck() {}
[HttpGet("authorize")] // Even without the explicit attribute, this will be protected by the one on the controller
public IActionResult KeyCheck() {}
}