ServiceStack:在 HTTP 请求中使用 headers 对每个请求进行身份验证

ServiceStack: Authenticate each request using headers in the HTTP request

我已经阅读了关于同一主题的 other posts,但我还没有真正清楚地了解如何最好地解决这个问题:

我有一个网络服务,当涉及到authentication/session时就是"stateless",这意味着客户端将在每个请求中发送两个字符串(在HTTP header中), AuthTokenDeviceUUID.

然后将这两个字符串与存储进行比较,如果找到,我们就知道是哪个用户。

1)

我想为我想要保护的每个服务使用 [Authenticate] 属性,然后应该在检查两个字符串的地方执行一个方法。

2)

如果我添加 [RequiredRole],还应该执行一个方法,我可以在其中访问 HTTP headers(两个字符串),这样我就可以进行查找。

我不确定如何以最简单和最干净的方式执行此操作。我不想创建 ServiceStack Session objects 等,我只想要一个方法,对于每个装饰服务,运行一个方法来检查身份验证状态。

如果你想在使用 [Authenticate][RequiredRole] 属性时 另外 执行其他操作,那么听起来你想要自定义 [MyAuthenticate] Request Filter attribute 两者都执行,即验证请求已通过身份验证并执行您的自定义功能,例如:

public class MyAuthenticateAttribute : AuthenticateAttribute
{
    public override async Task ExecuteAsync(IRequest req, IResponse res, object dto)
    {
        await base.ExecuteAsync(req, res, requestDto);

        var authenticated = !res.IsClosed; 
        if (authenticated)
        {
            //...
        }
    }
}

然后在需要额外功能的地方使用它而不是 [Authenticate]

[MyAuthenticate]
public class MyServices { ... }

但我个人会将属性中的逻辑分开:

public class MyLogicPostAuthAttribute : RequestFilterAsyncAttribute 
{
    public override async Task ExecuteAsync(IRequest req, IResponse res, object dto)
    {
        //...
    }
}

所以它们是明确的,可以独立于 [Authenticate] 属性分层,例如:

[Authenticate]
[MyLogicPostAuth]
public class MyServices { ... }

也可以这样组合:

[Authenticate, MyLogicPostAuth]
public class MyServices { ... }