5

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

有可能做相反的事情吗?即全局启用所有服务/请求的身份验证,然后选择性地禁用某些请求的身份验证(例如[NoAuthentication],在相关部分使用类似属性的东西)?

4

1 回答 1

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
    }
}
于 2013-10-16T13:02:52.880 回答