自定义身份验证中间件-如何检查请求是匿名还是授权? [英] Custom authentication middleware - how to check if request is anonymous or authorize?

查看:36
本文介绍了自定义身份验证中间件-如何检查请求是匿名还是授权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于自定义身份验证中间件-如何检查请求是匿名还是授权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆