No session if service doesn't require Authentication

I have a service method that doesn’t require authentication. For example “create post” that would create a post from the name “anonymous”. If an existing user calls “create post” I would like the post to have the name of the user.

My current implementaion have no Authenticate attribute on the method since its not required. But when a user with credentials calls this method (basic auth headers set and always send basicauth headers = true). Then no authentication is made and no session is created and my user still becomes “anonymous”.

Is there a way to make servicestack always authenticate if basicauth headers are provided so that my session gets created?

The [Authenticate] option is what triggers the auto-login “IAuthWithRequest” behavior. Without the attribute there’s no logic in the request pipeline to pre-authenticate HTTP Basic Auth Requests.

So you should be able to run the logic in PreAuthenticate() in a Global Filter to get the desired behavior:

You could just copy the logic or you re-use the existing logic in the BasicAuthProvider:

var auth = (IAuthWithRequest)AuthenticateService.GetAuthProvider(BasicAuthProvider.Name);
auth.PreAuthenticate(req,res);

Thanks, using a global filter seems to work.

Is this still the only option to have a Session when an authenticated user calls a service without the [Authorize] attribute?
If so, wouldn’t it be an idea to have a special attribute for these cases? As I understand it correctly, executing the PreAuthenticate logic in the Global Filter, will execute it twice in case of a secured service?

PreAuthenticate() is automatically called when a session is retrieved so this is no longer needed, also a flag is added to prevent duplicate executions.

But still the issue is there for services without an [Authenticate] attribute that they won’t populate Session if this service is called authenticated.