【问题标题】:Custom authentication middleware - how to check if request is anonymous or authorize?自定义身份验证中间件 - 如何检查请求是匿名的还是授权的?
【发布时间】:2020-11-10 22:32:55
【问题描述】:

我正在尝试编写自己的身份验证中间件代码。

在旧的 HttpModules 中,当请求“授权”页面时,我可以使用“OnAuthenticateRequest”。

我的中间件代码是这样的:

public async Task Invoke(HttpContext context)
{
    if (!context.User.Identity.IsAuthenticated)
    {
    }
}

...但这也会检查带有 [AllowAnonymous] 属性的请求的 IsAuthenticated。

如何从我的中间件中检查请求是否具有 [AllowAnonymous] 或 [Authorize] 属性?

我需要能够做一些类似...的事情

public async Task Invoke(HttpContext context)
{
    if (HasAuthorizeAttribute && !context.User.Identity.IsAuthenticated)
    {
    }
    await _next.Invoke(context);
}

谢谢。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-core


    【解决方案1】:

    有一种方法可以从中间件内部检查请求是否针对标记为 [匿名] 的页面。

    //inside your middleware
    var endpoint = context.GetEndpoint();
    if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() is object)
    {
        await _next(context);
        return;
    }
    

    在此博客上找到的原始解决方案:Anonymous Aware Middleware

    【讨论】:

    • 当将其与[AllowAnonymous] 属性结合使用时,endpoint?.Metadata?.GetMetadata&lt;IAllowAnonymous&gt;() 仍然始终为空。这在 .NET Core 5.x 中仍然有效吗?
    【解决方案2】:

    如果我理解你的意思正确,你正在寻找这样的东西:你想对控制器中的一些动作进行分类,一些动作可以在授权后执行,否则。

    在这种情况下,您可以在该操作的顶部设置[Authorize][AllowAnonymous]

    public class HomeController : Controller
    {
        [AllowAnonymous]
        public async Task Invoke(HttpContext context)
        {
            // all of codes here can be executed with unauthorized request(s).
            // code goes here...
        }
    
        [Authorized]
        public async Task Invoke_2(HttpContext context)
        {
            // all of codes here can be executed WHEN the request is authorized
            // code goes here...
        }
    }
    

    而且,如果您想授权所有将访问控制器的请求,您可以在控制器名称顶部设置[Authorize] 属性:

    [Authorize]
    public class HomeController : Controller
    {
        // this attribute is still required when you allow anonymous request(s)
        [AllowAnonymous]
        public async Task Invoke(HttpContext context)
        {
            // all of codes here can be executed with unauthorized request(s).
            // code goes here...
        }
    
        // you can remove [Authorize] attribute from this action, because
        // it's authorized by default
        public async Task Invoke_2(HttpContext context)
        {
            // all of codes here can be executed WHEN the request is authorized
            // code goes here...
        }
    }
    

    注意:因为您使用的是Task,所以最好将您的操作命名为以Async 结尾,例如:InvokeAsyncInvoke_2Async

    【讨论】:

    • 我认为这不能回答专门针对 ASP.NET MVC 中间件和检测请求是否针对具有 AllowAnonymous 属性的端点的问题。
    猜你喜欢
    • 2015-11-13
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    相关资源
    最近更新 更多