c# - Servicestack - 操作顺序、验证和请求过滤器

标签 c# servicestack servicestack-bsd

我检测到 RequestFilter 执行顺序有问题。

ServiceStack中的ValidationFeature是一个Plugin,只是注册了一个Global Request Filter。操作顺序指出全局请求过滤器在优先级<0的过滤器属性之后和优先级>=0

的过滤器属性之前执行

我的 BasicAuth 过滤器具有 -100 优先级,事实上,如果 Service 在类级别进行注释,则一切顺利,但在方法级别进行注释时会失败, 之后执行身份验证过滤器。

我正在使用 3.9.70 有什么快速解决方法吗?谢谢

最佳答案

当您在方法级别添加注解时,您正在创建一个Action Request Filter (因为您正在将注解添加到操作方法),它在 Order of Operations 中是操作 8,在其他过滤器运行之后。

5: Request Filter Attributes with Priority < 0 gets executed
6: Then any Global Request Filters get executed
7: Followed by Request Filter Attributes with Priority >= 0
8: Action Request Filters (New API only)


我建议的最佳解决方法是重新考虑您的服务结构。我想您遇到这些困难是因为您将未经身份验证的 api 方法与安全的 api 方法一起添加,因此使用方法级别的属性来控制身份验证。所以您可能正在做这样的事情您的类和属性会有所不同,这只是示例:

public class MyService : Service
{
    // Unauthenticated API method
    public object Get(GetPublicData request)
    {
        return {};
    }

    // Secure API method
    [MyBasicAuth] // <- Checks user has permission to run this method
    public object Get(GetSecureData request)
    {
        return {};
    }
}

我会采取不同的方式,将不安全和安全的方法分成 2 项服务。所以我用这个:

// Wrap in an outer class, then you can still register AppHost with `typeof(MyService).Assembly`
public partial class MyService
{
    public class MyPublicService : Service
    {
        public object Get(GetPublicData request)
        {
            return {};
        }
    }

    [MyBasicAuth] // <- Check is now class level, can run as expected before Validation
    public class MySecureService : Service
    {
        public object Get(GetSecureData request)
        {
            return {};
        }
    }
}

解决方案 - 延迟验证:

您可以通过创建自己的自定义验证功能来解决执行顺序问题,这将允许您推迟验证过程。我已经创建了一个功能齐全的自托管 ServiceStack v3 应用程序来演示这一点。

Full source code here .

本质上,我们实现了一个稍微修改过的版本,而不是添加标准的 ValidationFeature 插件:

public class MyValidationFeature : IPlugin
{
    static readonly ILog Log = LogManager.GetLogger(typeof(MyValidationFeature));
    
    public void Register(IAppHost appHost)
    {
        // Registers to use your custom validation filter instead of the standard one.
        if(!appHost.RequestFilters.Contains(MyValidationFilters.RequestFilter))
            appHost.RequestFilters.Add(MyValidationFilters.RequestFilter);
    }
}

public static class MyValidationFilters
{
    public static void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
    {
        // Determine if the Request DTO type has a MyRoleAttribute.
        // If it does not, run the validation normally. Otherwise defer doing that, it will happen after MyRoleAttribute.
        if(!requestDto.GetType().HasAttribute<MyRoleAttribute>()){
            Console.WriteLine("Running Validation");
            ValidationFilters.RequestFilter(req, res, requestDto);
            return;
        }

        Console.WriteLine("Deferring Validation until Roles are checked");
    }
}

配置使用我们的插件:

// Configure to use our custom Validation Feature (MyValidationFeature)
Plugins.Add(new MyValidationFeature());

然后我们需要创建自定义属性。你的属性当然会有所不同。您需要做的关键是调用 ValidationFilters.RequestFilter(req, res, requestDto); 如果您认为用户具有所需的角色并满足您的条件。

public class MyRoleAttribute : RequestFilterAttribute
{
    readonly string[] _roles;

    public MyRoleAttribute(params string[] roles)
    {
        _roles = roles;
    }

    #region implemented abstract members of RequestFilterAttribute

    public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
    {
        Console.WriteLine("Checking for required role");

        // Replace with your actual role checking code
        var role = req.GetParam("role");
        if(role == null || !_roles.Contains(role))
            throw HttpError.Unauthorized("You don't have the correct role");

        Console.WriteLine("Has required role");

        // Perform the deferred validation
        Console.WriteLine("Running Validation");
        ValidationFilters.RequestFilter(req, res, requestDto);
    }

    #endregion
}

为此,我们需要在 DTO 路由而不是操作方法上应用我们的自定义属性。因此,这将与您现在的做法略有不同,但仍应保持灵 active 。

[Route("/HaveChristmas", "GET")]
[MyRole("Santa","Rudolph","MrsClaus")] // Notice our custom MyRole attribute.
public class HaveChristmasRequest {}

[Route("/EasterEgg", "GET")]
[MyRole("Easterbunny")]
public class GetEasterEggRequest {}

[Route("/EinsteinsBirthday", "GET")]
public class EinsteinsBirthdayRequest {}

然后你的服务看起来像这样:

public class TestController : Service
{
    // Roles: Santa, Rudolph, MrsClaus
    public object Get(HaveChristmasRequest request)
    {
        return new { Presents = "Toy Car, Teddy Bear, Xbox"  };
    }

    // Roles: Easterbunny
    public object Get(GetEasterEggRequest request)
    {
        return new { EasterEgg = "Chocolate" };
    }

    // No roles required
    public object Get(EinsteinsBirthdayRequest request)
    {
        return new { Birthdate = new DateTime(1879, 3, 14)  };
    }
}
  • 因此,当我们调用 /EinsteinsBirthday 路由时,它 具有 MyRole 属性,验证将正常调用,如如果使用标准的 ValidationFeature

  • 如果我们调用路由 /HaveChristmas?role=Santa 那么我们的验证插件将确定 DTO 具有我们的属性并且不会运行。然后我们的属性过滤器触发,它将触发验证运行。因此顺序是正确的。

Screenshot

关于c# - Servicestack - 操作顺序、验证和请求过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21262049/

相关文章:

c# - 使用 ServiceStack 将命令输出流式传输到 ajax 调用

asp.net - 启动 ServiceStack 时无法加载类型 'ServiceStack.ServiceHost.IService'

c# - MVVM 单窗口应用程序中的编程导航

c# - 如何在 Action 中区分 ajax 请求和常规请求?

c# - 超过100位玩家在线时套接字失败

c# - 使用 OleDb 更新 Excel 工作表

c# - 在 F# 中使用绑定(bind)接口(interface)

servicestack - 解析 MVC Controller 中的 ServiceStack 服务

servicestack - 启用gzip/deflate压缩

c# - 在 ServiceStack 中访问自定义 ServiceRunner 的 HandleException 中的 responseDTO 类型