【问题标题】:ServiceStack authentication with both [Authenticate] and [ValidateApiKey] attributes具有 [Authenticate] 和 [ValidateApiKey] 属性的 ServiceStack 身份验证
【发布时间】:2015-05-07 15:34:48
【问题描述】:

我有一些用 [Authenticate] 属性装饰的端点。现在第三方客户端必须使用共享的 API 密钥来访问同一个端点。

由于这两种情况的代码完全相同,我想首先检查当前请求是否来自经过身份验证的用户,如果不是,则检查是否提供了有效的 API 密钥作为后备。

有没有办法为同一个端点同时使用 [Authenticate][ValidateApiKey] 属性?

类似:

[Authenticate | ValidateApiKey]
public long Post(MyDto request)
{
   // ....
}

【问题讨论】:

    标签: authentication servicestack api-key


    【解决方案1】:

    属性只能组合以添加功能,即它们不能用作后备或开关。要获得所需的行为,您的 [ValidateApiKey] 属性应该执行验证回退作为其实现的一部分,例如:

    public class ValidateApiKeyAttribute : RequestFilterAttribute
    {
        public override void Execute(IRequest req, IResponse res, object reqDto)
        {
            var session = req.GetSession();
            if (session == null || !session.IsAuthenticated)
            {
                //If not a valid key, execute the `[Authenticate]` attribute 
                //to handle failed response
                if (!CheckValidApiKey(req))
                    new AuthenticateAttribute().Execute(req,res,reqDto);
            }            
        }
    }
    

    注意:响应应该是引用类型(例如 DTO)或原始字符串而不是值类型。

    public object Post(MyDto request)
    {
       // ....
    }
    

    【讨论】:

    • 在我们的例子中,我们最终创建了两个端点以保持身份验证逻辑分离。但感谢澄清!
    猜你喜欢
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多