creare un attributo richiesta Filtro che imposta un flag nel contesto di richiesta dicendo di saltare l'autenticazione:
[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;
}
}
e creare una sottoclasse personalizzata di AuthenticateAttribute
che verifica quella bandiera nella richiesta:
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");
}
}
Usage:
[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
}
}
fonte
2013-10-16 13:02:52
Anche se ho votato questa risposta, la soluzione non ha funzionato per me. Chiama solo l'attributo MyAuthenticate e non riesce a chiamare l'attributo NoAuthenticate. – theoutlander
@theoutlander Vuoi dire che il metodo Execute nella classe NoAuthenticateAttribute non è invocato? Dove stai applicando i tuoi attributi MyAuthenticate e NoAuthenticate? –
Sì, è corretto. – theoutlander