Search code examples
authenticationservicestackapi-key

How to determine which ServiceStack AuthProvider gets used


I have written a CustomApiKeyAuthProvider that allows the use of an API key passed in the URL query string as:

GET https://example.com/resource/42?apikey=abc123etc

It is one of four auth providers that our system has.

Our AppHost config now looks like this:

_appHost.Plugins.Add(new AuthFeature(
    () => new AuthUserSession(), 
        new IAuthProvider[] {
            new CustomApiKeyAuthProvider(),
            new CredentialsAuthProvider(),
            new BasicAuthProvider(), 
            new JwtAuthProviderReader(_appHost.AppSettings)
            {
                AuthKey = Encoding.UTF8.GetBytes(OurEnvironment.TokenSecret),
            }
    }));

Our authenticated service calls are simply marked with:

[Authenticate]

They can, therefore, be authenticated using any provider.

The problem I'm having is that when I test it by making a request that looks like the one above, it does not try to use the new provider. I just get 401 Unauthorized.

What is it with the request that determines which provider is used, or does ServiceStack simply work through the list?

Thanks!


Solution

  • First you need to protect your Services with the [Authenticate] attribute.

    This requires that only an Authenticated User can access the Service. Users can be Authenticated using any of the registered Auth Providers, i.e. it's not specific to the request.

    You can find out which Auth Provider the User used to Authenticate from the AuthProvider property in their User Session, e.g:

    var authProviderUsed = base.Request.GetSession().AuthProvider;
    

    You can also assert the User needs to be Authenticated with a specific Auth Provider by specifying the AuthProvider Name in:

    [Authenticate(Provider="credentials")]