How can I prevent access to specific path with Ser

2019-08-10 19:51发布

问题:

When we want to prevent access to specific path with default asp.net authentication, we do:

<location path="routes.axd">
<system.web>
  <authorization>
    <allow roles="Agent"/>
    <deny users="*"/>
  </authorization>
</system.web>

How can we do with ServiceStack?

回答1:

There is no configuration to protect /paths in ServiceStack.

Using the [Authenticate] Attribute

You can protect services by adding the [Authenticate] attribute on either the Action:

class MyService : Service {
    [Authenticate] 
    public object Get(Protected request) { ... }
}

The Request DTO

[Authenticate] 
class Protected { ... }

Or the service implementation

[Authenticate] 
class MyService : Service {
    public object Get(Protected request) { ... }
}

Or by inheriting from a base class

[Authenticate] 
class MyServiceBase : Service { ... }


class MyService : MyServiceBase {
    public object Get(Protected request) { ... }
}

Using a Global Request Filter

Otherwise if you can use a global Request Filter if you wanted to restrict all requests any other way, e.g something like:

appHost.RequestFilters.Add((httpReq, httpResp, requestDto) =>
{
    if (IsAProtectedPath(httpReq.PathInfo)) {
       new AuthenticateAttribute()
         .Execute(httpReq, httpResp, requestDto);
    }
});