问题描述
我正在尝试编写自己的身份验证中间件代码.
I'm trying to write my own authentication middleware code.
在旧的HttpModules中,当请求授权"页面时,我可以使用"OnAuthenticateRequest".
In good old HttpModules, I could use "OnAuthenticateRequest" when a "Authorize" page was requested.
我的中间件代码是这样的:
My middleware code is something like this:
public async Task Invoke(HttpContext context)
{
if (!context.User.Identity.IsAuthenticated)
{
}
}
...但是这也会在具有[AllowAnonymous]属性的请求上检查IsAuthenticated.
... but that will also check IsAuthenticated on requests with [AllowAnonymous] attribute.
如何从中间件检查请求是否具有[AllowAnonymous]或[Authorize]属性?
How can I from my middleware, check if the request has attribute [AllowAnonymous] or [Authorize]?
我需要能够做类似...
I need to be able to do something like...
public async Task Invoke(HttpContext context)
{
if (HasAuthorizeAttribute && !context.User.Identity.IsAuthenticated)
{
}
await _next.Invoke(context);
}
谢谢.
推荐答案
有一种方法可以从中间件内部检查请求是否针对标记为[匿名]的页面.
There is a way to check, from inside your middleware, if the request is targeting a page marked as [Anonymous].
//inside your middleware
var endpoint = context.GetEndpoint();
if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() is object)
{
await _next(context);
return;
}
在此博客上找到的原始解决方案:匿名感知中间件
Original solution found on this blog: Anonymous Aware Middleware
这篇关于自定义身份验证中间件-如何检查请求是匿名还是授权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!