.NET Core : custom bearer filter for controller authentication
I'm new to this and want to make a simple bearer authentication on the controllers. So I extended the Startup.cs
:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseAuthorization();
app.UseAuthentication();
}
and created the filter:
public class BearerAuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter
{
private readonly string _bearerToken = ConfigurationManager.AppSettings["Token"];
public bool AllowMultiple { get; }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
//...
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
//...
}
}
public class AuthenticationFailureResult : IHttpActionResult
{
//...
}
But the controller ignored the code from the filter.
What am I doing wrong? I can't find any good and simple tutorial on how to implement bearer authentication...
Controller:
[ApiController]
[BearerAuthenticationFilter]
[Route("api/Test")]
public class TestController : ControllerBase
{
//...
}
EDIT:
I implemented the changes from @Tony Houdek but after I run the Controller it still dont do anything. Also I cant start the debugger inside the BearerAuthenticationFilter
.
My guess would be that you did not register the filter globally, so it is not automatically applied to all controller actions, you can either register it globally when registering the controllers, for example like this:
services.AddMvc(options =>
{
options.Filters.Add(new BearerAuthenticationFilter());
});
or you can apply the filter explicitly for specific controllers/actions using the BearerAuthenticationFilter attribute (do not forget to derive from Attribute class in your filter class):
[BearerAuthenticationFilter]
[ApiController]
[Route("api/Test")]
public class TestController : ControllerBase
{
//...
}
You can read more on action filters here: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs