[英].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
:所以我扩展了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.但是 controller 忽略了过滤器中的代码。
What am I doing wrong?我究竟做错了什么? I can't find any good and simple tutorial on how to implement bearer authentication...我找不到任何关于如何实现不记名身份验证的好而简单的教程......
Controller: 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.编辑:我实现了@Tony Houdek 的更改,但是在我运行 Controller 之后它仍然没有做任何事情。 Also I cant start the debugger inside the BearerAuthenticationFilter
.我也无法在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:我的猜测是您没有全局注册过滤器,因此它不会自动应用于所有 controller 操作,您可以在注册控制器时全局注册它,例如:
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 属性为特定控制器/操作显式应用过滤器(不要忘记从过滤器类中的 Attribute 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您可以在此处阅读有关操作过滤器的更多信息: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.