首页 文章

ServiceStack:如何查看当前请求的处理程序是否需要身份验证

提问于
浏览
2

我有一个使用旧API的web服务 . 几乎所有的服务处理程序都需要身份验证,因此我在服务级别使用Authenticate属性 .

我的所有服务都实现了一个自定义基本服务,它使用OnBeforeExecute来填充一些与身份验证相关的属性 .

有没有快速的方法来查看当前请求的处理程序是否需要在OnBeforeExecute方法中进行身份验证?

我宁愿不必使用反射查看属性,因为我理解这是一个相当慢的操作 . 我也期望ServiceStack系统已经在它的肚子里有这个信息:)


What I ended up doing

由于我的项目有服务,我使用Authenticate的ApplyTo参数来禁用某些处理程序的auth要求,我最终得到了以下内容 .

protected override void OnBeforeExecute(TRequestDto request)
{
    base.OnBeforeExecute(request);

    var attr = FilterAttributeCache.GetRequestFilterAttributes(request.GetType()).OfType<AuthenticateAttribute>().FirstOrDefault();
    if (attr != null)
    {
        ApplyTo reqmethod = base.Request.HttpMethodAsApplyTo();
        if ((attr.ApplyTo & reqmethod) == reqmethod)
        {
            //
            // do stuff that should only be done when 
            // the handler requires authentication
            //
        }
    }
}

1 回答

  • 2

    Authentication请求过滤器属性没有什么特别之处,除了lowest priority之外,它首先被执行 .

    ServiceStack确实维护了Request DTO所拥有的所有属性FilterAttributeCache,因此您可以使用此API来确定是否为特定服务定义了AuthenticateAttribute,例如:

    var hasAuth = FilterAttributeCache.GetRequestFilterAttributes(request.GetType())
       .OfType<AuthenticateAttribute>().FirstOrDefault() != null;
    

相关问题