ServiceStackを使用して、サービスの認証を選択的に有効[Authenticate]
にし、それぞれのクラス/メソッドに属性を適用して DTO とアクションを要求する必要があります。
逆にすることは可能ですか?つまり、すべてのサービス/リクエストの認証をグローバルに有効にしてから、一部のリクエストの認証を選択的に無効にします (たとえば[NoAuthentication]
、関連する部分の属性のようなものを使用します)?
ServiceStackを使用して、サービスの認証を選択的に有効[Authenticate]
にし、それぞれのクラス/メソッドに属性を適用して DTO とアクションを要求する必要があります。
逆にすることは可能ですか?つまり、すべてのサービス/リクエストの認証をグローバルに有効にしてから、一部のリクエストの認証を選択的に無効にします (たとえば[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
}
}