Skip to content

Instantly share code, notes, and snippets.

@lfmundim
Created December 26, 2019 12:03
Show Gist options
  • Save lfmundim/6e9fa039b92e0566fc740cb158bbf5ac to your computer and use it in GitHub Desktop.
Save lfmundim/6e9fa039b92e0566fc740cb158bbf5ac to your computer and use it in GitHub Desktop.

Usage

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() {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment