全局启用ServiceStack中的身份验证,但某些请求除外

时间:2013-10-16 08:28:41

标签: authentication servicestack

使用ServiceStack,我必须有选择地enable authentication服务,通过在相应的类/方法上应用[Authenticate]属性来请求DTO和操作。

是否可以做反向?即全局启用所有服务/请求的身份验证,然后有选择地禁用某些请求的身份验证(例如,在相关部分使用类似[NoAuthentication]属性的内容)?

1 个答案:

答案 0 :(得分:4)

创建请求过滤器属性,在请求上下文中设置一个标记,表示跳过身份验证:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class NoAuthenticateAttribute : RequestFilterAttribute {

    public NoAuthenticateAttribute() : this(ApplyTo.All) {}

    public NoAuthenticateAttribute(ApplyTo applyTo) : base(applyTo) {
        // execute this before any AuthenticateAttribute executes.
        // https://github.com/ServiceStack/ServiceStack/wiki/Order-of-Operations
        Priority = this.Priority = ((int) RequestFilterPriority.Authenticate) - 1;
    }

    public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
    {
        req.Items["SkipAuthentication"] = true;
    }
}

创建AuthenticateAttribute的自定义子类,检查请求中的该标志:

public class MyAuthenticateAttribute : AuthenticateAttribute {
    public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
    {
        if (!ShouldSkipAuthenticationFor(req))
            base.Execute(req, res, requestDto);
    }

    private bool ShouldSkipAuthenticationFor(IHttpRequest req)
    {
        return req.Items.ContainsKey("SkipAuthentication");
    }
}

用法:

[MyAuthenticate]
public class MyService : Service
{
    public object Get(DtoThatNeedsAuthentication obj)
    {
        // this will be authenticated
    }

    [NoAuthenticate]
    public object Get(DtoThatShouldNotAuthenticate obj)
    {
        // this will not be authenticated
    }
}