Authentication

5,656 views
Skip to first unread message

Andy McGoldrick

unread,
Feb 18, 2011, 10:08:14 AM2/18/11
to servic...@googlegroups.com
Hi,

was wondering what sort methods people used to authenticate both the calls to services and also what they would use to build Membership style functionality.

I had previously thought I wouldn't need to authenticate calls to my services and would rely on certificates and trusting calls from certificated callers - but I think I want to authenticate my callers using usernames and passwords.

I an thinking about using the Membership API from ASP.NET and creating my own provider - but it doesn't feel very natural to me - it seems like this is definitely something that a library should be used for  as its not an application specific component - but the only option I can see is the Membership Provider API approach.

I would use the Membership API inside my services to do the membership checks.  Ultimately I would want to try and do this using some AOP to inject this Aspect - but that is a long way away right now

Does anyone have any good solutions to they are using?


Thanks

Demis Bellot

unread,
Feb 18, 2011, 10:22:09 AM2/18/11
to servic...@googlegroups.com
Hi Andy,

Basically you should use the request filters to implement your authentication, I've got an example where I've implemented a simple BasicAuth here:


if (dto is Secure) { ...

Is an example on how you can force authentication for specific services. If you want to apply authentication on a 'group of services' I would either custom attribute the Request DTO or get it to implement an interface like 'IRequiresAuthentication' and then test on either the attribute or interface to force authentication.

I definitely intend to improve the authentication story in the near future to make it easier to plug-in different authentication providers/implementations as well as simplify its configuration. In the meantime that would be the approach I would take.

Cheers,
Demis

Andy McGoldrick

unread,
Feb 21, 2011, 8:10:33 AM2/21/11
to servic...@googlegroups.com
Excellent Demis, I will take these suggestions on board and go along that route.

Thanks again,


Andy

Andy McGoldrick

unread,
Feb 28, 2011, 5:24:13 PM2/28/11
to servic...@googlegroups.com
Hi,

while trying to follow the examples given above I tried to modify my  Configure   from


        public override void Configure(Container container)
        {
            // Signal advanced web browsers what HTTP Methods you accept
            base.SetConfig(new EndpointHostConfig()
            {
                GlobalResponseHeaders = 
                {
                    { "Access-Control-Allow-Origin""*" },
                    { "Access-Control-Allow-Methods""GET, POST, PUT, DELETE, OPTIONS" },
                }
            });

            container.Register<IResourceManager>(new ConfigurationResourceManager());
            container.Register<ICacheClient>(c => new MemoryCacheClient());

            log.InfoFormat("AppHost Configured: " + DateTime.Now);
        }

to

 public override void Configure(Container container)
        {
            base.SetConfig(new EndpointHostConfig()
            {
                GlobalResponseHeaders = 
                {
                    { "Access-Control-Allow-Origin""*" },
                    { "Access-Control-Allow-Methods""GET, POST, PUT, DELETE, OPTIONS" },
                }
            });

            container.Register<IResourceManager>(new ConfigurationResourceManager());
            container.Register<ICacheClient>(c => new MemoryCacheClient());

            log.InfoFormat("AppHost Configured: " + DateTime.Now);

            this.RequestFilters.Add((req, res, dto) =>
            {
                var userPass = req.GetBasicAuthUserAndPassword();
                if (userPass == null)
                {
                    res.ReturnAuthRequired();
                    return;
                }

                var userName = userPass.Value.Key;
                if (userName == AllowedUser && userPass.Value.Value == AllowedPass)
                {
                    res.SetPermanentCookie("ss-session", userName + "/" + Guid.NewGuid().ToString("N"));
                    //set session for this request (as no cookies will be set on this request)
                    req.Items["ss-session"] = userName + "/" + Guid.NewGuid().ToString("N");
                }
                else
                {
                    res.ReturnAuthRequired();
                }
            });
        }
}
}
When adding this I keep getting the following error:

Unhandled Exception: System.Net.WebException: The underlying connection was clos
ed: An unexpected error occurred on a receive. ---> System.IO.IOException: Unabl
e to read data from the transport connection: An existing connection was forcibl
y closed by the remote host. ---> System.Net.Sockets.SocketException: An existin
g connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size,
 SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 s
ize)
   --- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 s
ize)
   at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetriev
edStream, Boolean probeRead)
   --- End of inner exception stack trace ---
   at ServiceStack.ServiceClient.Web.ServiceClientBase.HandleResponseException[T
Response](Exception ex, String requestUri)
   at ServiceStack.ServiceClient.Web.ServiceClientBase.Send[TResponse](Object re
quest)
   at TestApp.Program.Main(String[] args) in C:\Repos\ysf\Web\TestApp\Program.cs
:line 25

No doubt I have made a simple mistake somewhere but I can't work out what or where.

Thanks

Andy

Demis Bellot

unread,
Feb 28, 2011, 5:31:15 PM2/28/11
to servic...@googlegroups.com
Hi Andy,

How are you running this? is this a Unit test using HttpListener? or an ASP.NET server like WebDev.WebServer20.exe or IIS?
The exception looks like it can't make a connection at all, can you see if you can access it with your browser and make sure you have the correct urls?

Otherwise if you're using a HttpListener, run a test like this to leave the HttpListener on for enough time to call the url with a web browser.

[Test]
[Ignore("Helps debugging when you need to find out what is going on")]
public void Run_for_30secs()
{
Thread.Sleep(30000);
}

Cheers,
Demis

Andy McGoldrick

unread,
Feb 28, 2011, 5:38:05 PM2/28/11
to servic...@googlegroups.com, Demis Bellot
Hi Demis,

thanks for the reply.

I have it hosted in IIS 7I can get to 

and see what I was expecting.

I have a ConsoleApp as my test harness it contains the following:
        static void Main(string[] args)
        {
            using (var client = new JsonServiceClient(BaseUrl))
            {
                client.HttpMethod = HttpMethod.Get;
                try
                {
                    var jsonResponse =
                    client.Send<UserResponse>(new User() { Details = new UserDetail() { Email = "and@here", Name = "ansmdf" } });
                }
                catch (ServiceStack.ServiceClient.Web.WebServiceException wse)
                {
                    throw;
                }
            }
            Console.ReadLine();
        }
As I said, with the original version of the Configure() method everything worked.

Andy

ruionwriting

unread,
Mar 25, 2011, 8:22:40 AM3/25/11
to ServiceStack .NET Open Source REST Web Services Framework
Hi Andy,

it seams that we both have the same practical dilemma right now
(http://groups.google.com/group/servicestack/browse_thread/thread/
86fa304a95a2b561#). My key goals are:

- Authenticate client access to my API;
- Client must supply a user name, an api key;
- Base on the supplied values (request header) I want to identity if
the client is valid to use the service. The client/user information is
stored on a database;
- Additionally I want to restrict certain methods to specific set of
clients.

Rui

On Feb 28, 10:38 pm, Andy McGoldrick <andy.mcgoldr...@gmail.com>
wrote:
> Hi Demis,
>
> thanks for the reply.
>
> I have it hosted in IIS 7I can get tohttp://localhost/MvcQuickStart/servicestack/json/metadata?op=User
>
> <http://localhost/MvcQuickStart/servicestack/json/metadata?op=User>and see
> what I was expecting.
>
> I have a ConsoleApp as my test harness it contains the following:
>
>         static void Main(string[] args)
>         {
>             using (var client = new JsonServiceClient(BaseUrl))
>             {
>                 client.HttpMethod = HttpMethod.Get;
>                 try
>                 {
>                     var jsonResponse =
>                     client.Send<UserResponse>(new User() { Details =
> new UserDetail() { Email = "and@here", Name = "ansmdf" } });
>                 }
>                 catch (ServiceStack.ServiceClient.Web.WebServiceException wse)
>                 {
>                     throw;
>                 }
>             }
>             Console.ReadLine();
>         }
>
> As I said, with the original version of the Configure() method everything
> worked.
>
> Andy
>
> >> On 21 February 2011 13:10, Andy McGoldrick <andy.mcgoldr...@gmail.com>wrote:
>
> >>> Excellent Demis, I will take these suggestions on board and go along that
> >>> route.
>
> >>> Thanks again,
>
> >>> Andy
>
> >>> On 18 February 2011 15:22, Demis Bellot <demis.bel...@gmail.com> wrote:
>
> >>>> Hi Andy,
>
> >>>> Basically you should use the request filters to implement your
> >>>> authentication, I've got an example where I've implemented a simple
> >>>> BasicAuth here:
>
> >>>>https://github.com/ServiceStack/ServiceStack/blob/master/tests/Servic...

Andy McGoldrick

unread,
Mar 25, 2011, 10:02:16 AM3/25/11
to servic...@googlegroups.com
Hi Rui,

it seems that we do have very similar needs.

I have discussed this Demis a bit further, but my issues stem from hosting the ServiceStack services within an ASP.Net web site that has Forms authentication switched on.

What happens is that, when ServiceStack raise a 302, when a user is not authenticated, IIS redirects to the forms login page, which the Service Stack clients then receive instead of a 302.

IIS 6 allowed different parts of your site to have different authentication setup, but I don't think IIS 7 and higher allows this.

I haven't looked into it recently - but jsut based on a feeling - nothing to back that up - it feels like there should be some way in the HTTP stack to detect a redirect and if the originating URL is within my ServiceStack services, ignore the redirect.

This all seems like more trouble than it's worth, so for the moment I am working on the principle of a separate website within IIS for hosting the services, this can then be configured without forms authentication.

Andy

ruionwriting

unread,
Mar 25, 2011, 10:27:28 AM3/25/11
to ServiceStack .NET Open Source REST Web Services Framework
Hi Andy,

My approach is in fact to have always the API in a separate website,
although on IIS, it could work, converting /api to an website with an
separate app pool. This could be hard, I don't if it's your case, on
shared hosting environment. Currently I'm exploring another
possibility, to extend RestServiceBase creating for example an
abstract class called AuthRestServiceBase that would implement my
validation needs.

My bases come from several approaches that I find (here's on
http://code.google.com/p/servicestack/issues/detail?id=41) and in the
fact that we can access the original request any time:

using SPS.ServiceCore.API.ServiceModel.Operations;
using SPS.ServiceCore.API.ServiceModel.Types;
using ServiceStack.ServiceInterface;

using System.Collections.Generic;

namespace SPS.ServiceCore.API.ServiceInterface
{
public class CustomersService : RestServiceBase<Customers>
{
public override object OnGet(Customers request)
{
string z = base.RequestContext.GetHeader("User-Agent");

#region Create dummy data

List<Customer> customers = new List<Customer>();

Customer customer = new Customer()
{
ContactName = "Customer 1",
City = "Lx"
};

customers.Add(customer);

customer.ContactName = "Customer 2";
customer.City = "Ptm";
customers.Add(customer);

#endregion

//return new CustomersResponse { Customers =
DbFactory.Exec(dbCmd => dbCmd.Select<Customer>()) };
return new CustomersResponse { Customers = customers };
}
}
}

In 'z', just for the example, I can what i need. I think that this
extension class should be located in my service interface
(API.ServiceInterface). My solution is huge (EF + Repository +
Specification + ... several other patterns) and the API is the
smaller, but not less important aspect off the all. Concerning the API
structure I have the following projects (this was inspired by the
samples provided with the stack):

- API (the service host it self that runs on IIS or other);
- API.ServiceInterface (the actual implementation of my services);
- API.ServiceModel (where I my operations and types defined)

Demis, am I going in the right way?

Rui
> ...
>
> read more »

Demis Bellot

unread,
Mar 25, 2011, 11:07:56 AM3/25/11
to servic...@googlegroups.com
Hi Rui,

- API (the service host it self that runs on IIS or other);
- API.ServiceInterface (the actual implementation of my services);
- API.ServiceModel (where I my operations and types defined)

Yep this is the way I would recommend structuring your project.

As for the authentication, whether you use a base class or request filter it doesn't matter both would work - just a matter of preference.

Just as a matter of code-design, I would personally I would wrap all your EF + Auth logic behind an IAuthProvider-like class & interface and have that registered as a normal dependency in Funq IOC in your AppHost.Configure().

Note: when setting up your cookies you will need to set them on the response. You can do this by either using either of the Request or Response filters, i.e:

this.RequestFilters.Add((req, res, dto) =>
{
res.SetPermanentCookie("ss-session", sessionKey);
});

Or you can return custom headers in your service, which you do by returning a HttpResult that lets you modify the Headers in the Http Response, e.g:

public class CustomersService : RestServiceBase<Customers>
{
public override object OnGet(Customers request)
{
return new HttpResult(dtoResponse) {
Headers = { HttpHeaders.SetCookie, "CookieName=CookieValue;path=/"}
}
}
}


Now the other way to do authentication is explicitly without using cookies (which is what we did at mflow) where you would always have a property on your request DTO for the webservices you wanted to protect.
We would have an interface like

interface IRequiresSession {
    Guid SessionId { get; }
}

Which our web services request dto's would implement, e.g.

class Customers : IRequiresSession {
    Guid SessionId { get; set; }

    string Id { get;set;}
}

This allows your request filter or base class to generically determine which requests need to be authenticated, e.g.

this.RequestFilters.Add((req, res, dto) =>
{
    var requiresSession = req as IRequiresSession;
    if (requiresSession == null) return;

    var authProvider = container.Resolve<IAuthProvider>();
    if (!authProvider.IsValidSession(authProvider.SessionId))
    {
       return res.ReturnAuthRequired();
    }
});


Hope this helps!

Cheers,
Demis

Andy McGoldrick

unread,
Mar 25, 2011, 11:21:48 AM3/25/11
to servic...@googlegroups.com
Hi Demis,

would you set the sessionid and pass it back to the client so that it would be supplied in successive calls?

If so how/when and what about time out of the sessionid?

Cheers

Andy

Demis Bellot

unread,
Mar 25, 2011, 11:31:27 AM3/25/11
to servic...@googlegroups.com
So I would have a LoginService that as part of a successful response would return the SessionId to the client then, which they would keep and pass in on subsequent calls.

This is the approach we took at mflow, using explicit dto properties - this was before ServiceStack had RequestFitlers / cookies support :).

It was sure easy to debug and we didn't have to sniff packets since the SessionId is pre-populated on the dto, easy to see/debug/test.

The cookie approach is more transparent/REST-y :), although you will likely need a few trips to Fiddler to make sure you've set it up right.

Cheers,

Rui Marques

unread,
Mar 25, 2011, 11:56:09 AM3/25/11
to ServiceStack .NET Open Source REST Web Services Framework
Hi again Demis, Andy,

(I'm having a lot of fun discovering this stack, as an WCF dependent
for several years, change is coming to my life :) , nice work)

I feel that we are getting in the right way with this discussion but
let me summarize the scenarios:

1. We need to authorize the 'clients' properly to user our services;
2. The client would have an supplied API key and user name that allows
it to call the service;
3. We could have LoginService that would return a session ID to be
used on the following service calls;
4. We would have also the need to have services roles for example we
have a service that have several methods but we might want to restrict
access for some of them based on the client type (customer, supplier,
etc);
5. We don't want to duplicate code on each service to comply (only in
the restriction exceptions? just an idea) with the previous;
6. Just as a matter of code-design, I would personally I would wrap
all your EF + Auth logic behind an IAuthProvider-like class &
interface and have that registered as a normal dependency in Funq IOC
in your AppHost.Configure().

My major goal is to achieve this requirements keeping a good code-
design.

Rui

On Mar 25, 3:31 pm, Demis Bellot <demis.bel...@gmail.com> wrote:
> So I would have a LoginService that as part of a successful response would
> return the SessionId to the client then, which they would keep and pass in
> on subsequent calls.
>
> This is the approach we took at mflow, using explicit dto properties - this
> was before ServiceStack had RequestFitlers / cookies support :).
>
> It was sure easy to debug and we didn't have to sniff packets since the
> SessionId is pre-populated on the dto, easy to see/debug/test.
>
> The cookie approach is more transparent/REST-y :), although you will likely
> need a few trips to Fiddler to make sure you've set it up right.
>
> Cheers,
>
> On Fri, Mar 25, 2011 at 3:21 PM, Andy McGoldrick
> <andy.mcgoldr...@gmail.com>wrote:
>
>
>
>
>
>
>
> > Hi Demis,
>
> > would you set the sessionid and pass it back to the client so that it would
> > be supplied in successive calls?
>
> > If so how/when and what about time out of the sessionid?
>
> > Cheers
>
> > Andy
>
> ...
>
> read more »

Demis Bellot

unread,
Mar 25, 2011, 1:00:09 PM3/25/11
to servic...@googlegroups.com
Hi Rui,

I'm glad to hear it :)  Yeah it serves me quite well from sometime as well, but its often hard to structure the documentation properly and explain the benefits - Something I need to find more time for and get better at!

Note: a lot of your requirements and how you ultimately handle the authentication is up to your coding style preference.
What's important is to be able to execute auth/validation logic for every request and that you have access to the container so you can pull out your re-usable AuthenticationService code to validate the request.

Something to keep in mind is that in ServiceStack we're free of ASP.NET configuration authentication providers and the like, so there is no special magic behaviour you need to meet or special configuration to get the desired behaviour you want, you simply just have to code for the behaviour you want. The UserSession classes is similar to the approach we took at mflow, though we ultimately stored our authentication in one of the ServiceStack caching providers.


So based on your requirements:

2. The client would have an supplied API key and user name that allows
it to call the service;
3. We could have LoginService that would return a session ID to be
used on the following service calls; 

It sounds like you want this information passed as part of an explicit initial request into your LoginService, which will check to ensure this information is valid, if it is it should create a new SessionId (i.e. Guid) and store a reference the the user and perhaps their Roles, ClientType, etc i.e. any other information the IAuthProvider will need as per your fine-grained authentication requirements.

4. We would have also the need to have services roles for example we
have a service that have several methods but we might want to restrict
access for some of them based on the client type (customer, supplier,
etc);

From here you're going to want to access the auth provider and apply your specific style of validation. 
I would do something like use the SessionId to retrieve the user's Session (prepared in the login) and use that to work out what type of client and whether they have access or not.
If different services have different authorization rules, you might want to differentiate this by using a custom attribute on the request DTO:

So If you're applying the validation logic in a baseclass you can throw a C# exception for unauthorized requests, e.g:

[CustomAuth("SpecialAccess")]
class AnyRequestDto : IRequiresSession
{
    public Guid SessionId {get;set;}
}

public class ServiceBase<T> {
    public IAuthProvider AuthProvider { get; set; } // Injected by IOC

public object Execute(TRequest request)
{
try
{
    var requiresSession = req as IRequiresSession;
    if (requiresSession != null) 
            {
                if (!AuthProvider.IsValid(requiresSession.SessionId)) 
                    throw new UnAuthorizedException();

                var attrs = requestType.GetCustomAttributes(typeof(CustomAuthAttribute), true);
                if (attrs.Length > 0) {
                    var authAttr = (CustomAuthAttribute)atts[0];
                    if (!AuthProvider.IsValid(requiresSession.SessionId, authAttr.ClientType))
                        throw new UnAuthorizedException();
                }
            }

    return Run(request);
}
catch (Exception ex)
{
return HandleException(request, ex);
}
}

Here is the source code of the ServiceBase.cs and RestServiceBase.cs classes, which just provides convenience exception handling for your services:


They're kept in a separate 'user high-level' assembly, separated from the framework on purpose as I expect different people may want to tweak it to their own needs or subclass it as desired.



this.RequestFilters.Add((req, res, dto) =>
{
    var requiresSession = req as IRequiresSession;
    if (requiresSession != null) 
    {
if (!AuthProvider.IsValid(requiresSession.SessionId)) {
               res.ReturnAuthRequired(); 
               return;
        }

var attrs = requestType.GetCustomAttributes(typeof(CustomAuthAttribute), true);
if (attrs.Length > 0) {
   var authAttr = (CustomAuthAttribute)atts[0];
   if (!AuthProvider.IsValid(requiresSession.SessionId, authAttr.ClientType)) {
               res.ReturnAuthRequired(); 
               return;
            }
}
    }
});

5. We don't want to duplicate code on each service to comply (only in
the restriction exceptions? just an idea) with the previous;
6. Just as a matter of code-design, I would personally I would wrap
all your EF + Auth logic behind an IAuthProvider-like class &
interface and have that registered as a normal dependency in Funq IOC
in your AppHost.Configure().
My major goal is to achieve this requirements keeping a good code-
design.

Yeah I agree that should always be the goal. What I'm alluding to is that you should provide your own custom class + interface to do this, insulating the fact that its actually works using EF behind the scenes.
e.g. based on the above source code, we would need a custom class that implements this:

interface IAuthProvider {
    bool IsValid(Guid sessionId);
    bool IsValid(Guid sessionId, string clientType);
}

then in your AppHost you would need something like this:

public override void Configure(Container container)
{
    container.Register<IAuthProvider >(new MyCustomEfAuthProvider(someConfigThisNeeds));
}

Note: I'd probably have the above interface a little different API myself to take inconsideration that you only want 1 db call (or my personal pref 1 redis call :) at most (if possible) to handle, but I'll leave that up to you to work out.

Anyway I hope this helps make things a little clearer!
If you manage to get this up an running I would really appreciate if you can share your approach in a blogpost or something so we can share the knowledge and help others looking to do the same thing :)

Thanks,

Rui Marques

unread,
Mar 25, 2011, 1:27:28 PM3/25/11
to servic...@googlegroups.com, Demis Bellot
Hi Demis,

You've posted precious information that I believe is pointing to the perfect solution. IoC is something that I'm being avoid to long, it's time to make that change. I'm going work on this and I'll give some feedback soon.

For someone new to this topic I recommend this article from Joel Abrahamsson that helped me to clarify some points about the subject.

Thanks,

Rui

Demis Bellot

unread,
Mar 25, 2011, 1:36:34 PM3/25/11
to servic...@googlegroups.com
Hi Rui,

I think you will find Funq a very easy IOC to use. It's made by Daniel Cazzulino who has a knack of creating easy to use intuitive APIs and luckily has got a screencast of how he built Funq, which I think will be a good watch if you're new to IOC and Funq:

There really isn't much to it, i.e. whatever you register in your AppHost gets automatically injected in your services.
It promotes re-use and reduces the friction in the 'construction of objects' as you only need to do it once.

We specifically chose Funq because its small, simple to use and fast. I also don't agree with a lot of the more complex IOC's out there as a lot of the time the added features make your code less explicit, harder to configure, understand and debug and comes with a performance cost.

Cheers,

Rui Marques

unread,
Mar 25, 2011, 1:45:10 PM3/25/11
to servic...@googlegroups.com, Demis Bellot
Demis,

Can you supply the code examples in a working solution/project? I hope to post my result implementation with EF for your evaluation our previous use on servicestack.net samples.


Rui

Rui Marques

unread,
Mar 25, 2011, 1:57:31 PM3/25/11
to servic...@googlegroups.com, Demis Bellot
Here is my current test code with the project structure I wrote about.
TestSolution.zip

Demis Bellot

unread,
Mar 26, 2011, 1:10:17 AM3/26/11
to servic...@googlegroups.com
Hi Rui,

I've added a Public, Protected and ProtectedClientType services with varying different authentication privillages.

I've demonstrated the IAuthProvider using an InMemoryAuthProvider which you should be able to follow and be able to refactor the desired logic into your own IAuthProvider with an EF backend.

Look at the AuthenticationTests for integration tests demonstrating the various levels of authentication.

It should hopefully be pretty self-explanatory if not, let me know and I'll clarify.

So after you get a working system up and running, I would appreciate if you can publish a documentation/tutorial on how to implement this Authenticaion in ServiceStack.

Cheers,
Demis



On Fri, Mar 25, 2011 at 5:57 PM, Rui Marques <r...@ruionwriting.net> wrote:
Here is my current test code with the project structure I wrote about.



TestSolution.zip

Rui Marques

unread,
Mar 28, 2011, 4:51:47 AM3/28/11
to servic...@googlegroups.com, Demis Bellot
Hi Demis,

Thanks in advance, i looked to the good and now I'm going to do my implementation. After i finish i'll write an tutorial about my approach with the EF back-end. I'm thinking on publish this on my blog making reference to service stack project and this discussion. I'll also post the code here with the tutorial. I't s ok for you?

Rui

Ps: is there an servicestack.net logo to use to spread the word?

mythz

unread,
Mar 28, 2011, 5:27:08 AM3/28/11
to servic...@googlegroups.com, Demis Bellot
Hey Rui,

Yep that's totally ok :) Yeah any documentation you can provide to make it easier for others looking to do the same thing is more than helpful thanks.
Let me know if you still have any troubles in getting started.

I've got a fair few image assets that are used on the http://www.servicestack.net website at:

Some of the ones that you might be interested in:

Just logo:

With text:

The Paint.NET files (.pdn) are also available from the same directory, feel free to cut your own as you see fit.

Cheers,
Demis


Rui Marques

unread,
Mar 28, 2011, 6:57:36 AM3/28/11
to servic...@googlegroups.com, Demis Bellot
Demis,

The changes test solutions works fine but the same exact code (possible I'm missing something) doesn't build. Error:
Error 1 'SPS.ServiceCore.API.ServiceInterface.SPSServiceBase<TRequest>.OnBeforeExecute(TRequest)': no suitable method found to override E:\Projects\SPS\SPS.ServiceCore\SPS.ServiceCore.API.ServiceInterface\SPSServiceBase.cs 10 24 SPS.ServiceCore.API.ServiceInterface
 I've checked the ShareLibs folder, all the same. The same result for project dependencies. Something wrong with RestServiceBase<TRequest>?


Rui

Demis Bellot

unread,
Mar 28, 2011, 7:31:52 AM3/28/11
to servic...@googlegroups.com, Rui Marques
Hi Rui,

Yeah that was a change I recently made to ServiceStack.ServiceInterface.dll to make it easier to provide a generic validation routine without having to overload each method. The new dll should be in the zip package I sent.

Had I not forgotten to check the changes in on the weekend, the source code would be available (in the ServiceBase.cs and RestServiceBase.cs) at the ServiceStack.Contrib project :)

Anyway, I've re-built from the latest source code and you can find the updated ServiceStack.ServiceInterface.dll attached, it will be included in the next ServiceStack release.


Cheers,
Demis

ServiceStack.ServiceInterface.zip

Rui Marques

unread,
Mar 28, 2011, 7:37:36 AM3/28/11
to servic...@googlegroups.com, Rui Marques, Demis Bellot
Worked!

Thanks Demis.

Rui Marques

unread,
Mar 28, 2011, 9:40:16 AM3/28/11
to servic...@googlegroups.com, Rui Marques, Demis Bellot
Hi Demis,

Is it possible to apply similar access restrictions do metadata/ in order to supply just the info for a particular role (ex: public, reseller, private, etc)? Security by obscurity is a prime rule for me.


Rui

Demis Bellot

unread,
Mar 28, 2011, 9:56:24 AM3/28/11
to servic...@googlegroups.com, Rui Marques
I can add an option to disable metadata page completely. But as this is a foreign bespoke requirement you'll have to provide your own specific API page.

- Demis

Rui Marques

unread,
Mar 29, 2011, 7:30:39 AM3/29/11
to servic...@googlegroups.com, Rui Marques, Demis Bellot
Having that as an option on the handler would be great. That way I would disable when build as release.

Demis Bellot

unread,
Mar 29, 2011, 7:31:53 AM3/29/11
to servic...@googlegroups.com, Rui Marques
Agreed, it's high up on the TODO list, which I expect it to deliver in the next release.



On Tue, Mar 29, 2011 at 12:30 PM, Rui Marques <r...@ruionwriting.net> wrote:
Having that as an option on the handler would be great. That way I would disable when build as release.



Rui Marques

unread,
Mar 31, 2011, 9:14:18 AM3/31/11
to servic...@googlegroups.com, Rui Marques
Demis,

I haven't forgot this, i'm implementing a complete structure with unit testing and that complies with my architectural vision for the project i'm working on. I'm using repository specification, unit of work patterns, etc and I home at the end do make a complete tutorial providing the guidelines, references, etc to share with the community.  


Rui

Demis Bellot

unread,
Mar 31, 2011, 9:19:11 AM3/31/11
to servic...@googlegroups.com
Hi Rui,

It sounds like you're progressing quite well - glad to hear it!

Don't worry about the timing for this at all, the important bit is to make sure you get the services set-up and working as how you want it, everything else can come later - i.e. after you run into some free time and are familiar with how everything fits together :)

Cheers,
D

Ged Wed

unread,
Apr 4, 2011, 3:49:32 PM4/4/11
to servic...@googlegroups.com, Demis Bellot
Guys have a look a how RavenDB does the authorisation stuff.
http://ravendb.net/bundles/authorization
Its a very nice pattern i think.

The code is there in Raven and so we coudl fork it and make a very nice little authourisation for Service stack.

Also i normally using a noncing pattern. This prevents replay attacks and also (if i choose) means i dont need a session in the server at all.
Every call requires a token as part of the header (or method sig).
The token is using noncing and its heavily crypt with salt.
Its is the users id, etc and roles all tied up, but its is cryptoed on EVERY request, and sends a new one back.
Its a very small overhead and MUCH more secure.
they have to login in initially to get their first one though.

I have it lying around someone and so could pump it into Github if there is wnough interest.

G

Andy McGoldrick

unread,
Apr 4, 2011, 6:11:01 PM4/4/11
to servic...@googlegroups.com
Ged,

I would love a look at that, so if you do put it in Github somewhere, please let me know.

Do you have much experience with RavenDB?  Its something we are looking at but if I am honest I don't feel that I understand the concepts around designing the documents well enough and that its holding me back.

Andy

mythz

unread,
Apr 5, 2011, 9:59:00 AM4/5/11
to servic...@googlegroups.com
Yeah that would be awesome to see it in GitHub somewhere as well.

If you don't have a better place to put it, it would make an ideal addition to:

Which is used to store any Useful user contributions that may be useful for ServiceStack uers :)

D

M. Herold

unread,
Apr 11, 2012, 5:40:19 PM4/11/12
to servic...@googlegroups.com
Hey Demis

I'm looking at auth and I want to clarify my approach, get your thoughts and ask a couple questions.

First of all, what I'm doing for authentication is along the lines of what you posted here: I'm using a request filter for all of my services which implements a sort of two-legged OAuth, or OAuthLite as I've seen it called. Basically, expecting the oauth_etc variables to be passed in through the headers, parses the header, passes the values into a little oauthlite validation function, and if things are peachy, sets a quick bool in the DTO called <secure>. From there, when I'm processing my DTOs in their respective services, they error if !<secure>, sending back a response DTO detailing the error.

What I don't like about this is two-fold: 1) I'm not returning anything based in the headers, e.g. a status code, description and some WWW-Authentication header. 2) I'm forced to have my request DTOs implement an IRequiresAuthentication interface, which alters the metadata documentation in a way that seems sloppy. Someone looking at that might a) wonder what the secure bool value is and b) assume that setting it true makes it secure? Or something. Is there either a way to hide this <secure> variable from the outside or possibly a better way I could be doing this altogether?

Thanks in advance
Michael

On Friday, February 18, 2011 9:22:09 AM UTC-6, mythz wrote:
Hi Andy,

Basically you should use the request filters to implement your authentication, I've got an example where I've implemented a simple BasicAuth here:


if (dto is Secure) { ...

Is an example on how you can force authentication for specific services. If you want to apply authentication on a 'group of services' I would either custom attribute the Request DTO or get it to implement an interface like 'IRequiresAuthentication' and then test on either the attribute or interface to force authentication.

I definitely intend to improve the authentication story in the near future to make it easier to plug-in different authentication providers/implementations as well as simplify its configuration. In the meantime that would be the approach I would take.

Cheers,
Demis



On Fri, Feb 18, 2011 at 3:08 PM, Andy McGoldrick <andy.mc...@gmail.com> wrote:
Hi,

was wondering what sort methods people used to authenticate both the calls to services and also what they would use to build Membership style functionality.

I had previously thought I wouldn't need to authenticate calls to my services and would rely on certificates and trusting calls from certificated callers - but I think I want to authenticate my callers using usernames and passwords.

I an thinking about using the Membership API from ASP.NET and creating my own provider - but it doesn't feel very natural to me - it seems like this is definitely something that a library should be used for  as its not an application specific component - but the only option I can see is the Membership Provider API approach.

I would use the Membership API inside my services to do the membership checks.  Ultimately I would want to try and do this using some AOP to inject this Aspect - but that is a long way away right now

Does anyone have any good solutions to they are using?


Thanks

M. Herold

unread,
Apr 11, 2012, 5:42:25 PM4/11/12
to servic...@googlegroups.com
To clarify, I've played a little with returning different headers and status codes, but they're not limiting the values I'm returning in my services, e.g:

            res.StatusCode = 401;
            res.AddHeader("WWW-Authenticate""Basic realm=\"realm\"");
            return;

Demis Bellot

unread,
Apr 11, 2012, 5:58:44 PM4/11/12
to servic...@googlegroups.com
Have you had a chance to look at ServiceStack's built-in Auth Provider model yet?

There's a demo app which uses it at:

Which is now also deployed to AppHarbor at:

Whether you choose to use Attributes vs Interfaces or Request Filters vs Base Classes is a matter of preference.
Although if I were going to implement it from scratch I would make use of RequestFilter Attributes which will allow you to mark with a custom attribute (on the DTO or the service) which services need authenticating:

Cheers,

M. Herold

unread,
Apr 26, 2012, 2:52:27 PM4/26/12
to servic...@googlegroups.com
I've looked at the AuthProvider model, but I'm not certain it's what I'm looking for exactly as I'm trying to implement OAuth on top of it. Maybe I just haven't been able to wrap my head around it. But with deadlines looming, I've just resigned myself to sticking with my work-around. I do still have a question, though:

Is there a way to share data from request filter to HTTP verb method without passing that data into the DTO? I'm branching to different databases based on which consumer authenticates with the API, and having their consumer key tacked onto the DTO in addition to this secure boolean is getting a little out-of-hand in the ideal territory. I might nix if(dto.secure) in favor of if(dto.consumerKey != null) just to keep the internal-variables-in-my-DTO to a minimum, but there must be a better way. Hrmph.

Now that I think of it, I should really just be passing the connection string from request filter to http verb, but I'm opting for multiple DB hits to keep transparency down (I use the consumer key to grab the db connection string). Then again, I guess the additional field could be obfuscated as something like <metadata> in a string. Weird design issues. 

Thanks as always
Michael

Demis Bellot

unread,
Apr 26, 2012, 2:59:59 PM4/26/12
to servic...@googlegroups.com
You can communicate between filters and services by storing info in the IHttpRequest.Items dictionary.
Which you can access in your services via:

var httpReq = base.RequestContext.Get<IHttpRequest>();

Cheers,

M. Herold

unread,
Apr 26, 2012, 3:20:09 PM4/26/12
to servic...@googlegroups.com
Wonderful, time to slap this together and get back to the front-end where I apparently belong ;)

Thanks again again again, man.
Reply all
Reply to author
Forward
0 new messages