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

M4N*_*M4N 5 authentication servicestack

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

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

Mik*_*ock 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并创建一个自定义子类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");
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

[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
    }
}
Run Code Online (Sandbox Code Playgroud)