5
使用ServiceStack,我必須在服務選擇性enable authentication,通過在各自的類/方法施加[Authenticate]
屬性請求的DTO和行動。全局啓動認證在ServiceStack,除了一些請求
是否有可能做相反的事情?即全局啓用所有服務/請求的身份驗證,然後選擇性地禁用某些請求的身份驗證(例如,使用類似於相關部分的[NoAuthentication]
屬性)?
使用ServiceStack,我必須在服務選擇性enable authentication,通過在各自的類/方法施加[Authenticate]
屬性請求的DTO和行動。全局啓動認證在ServiceStack,除了一些請求
是否有可能做相反的事情?即全局啓用所有服務/請求的身份驗證,然後選擇性地禁用某些請求的身份驗證(例如,使用類似於相關部分的[NoAuthentication]
屬性)?
創建請求過濾器屬性,設置標誌在請求上下文中說跳過認證:
[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
}
}
雖然我投了這個答案,但解決方案並不適合我。它僅調用MyAuthenticate屬性,並且未能調用NoAuthenticate屬性。 – theoutlander
@theoutlander你的意思是不調用NoAuthenticateAttribute類中的Execute方法?你在哪裏應用你的MyAuthenticate和NoAuthenticate屬性? –
是的,這是正確的。 – theoutlander