How to use ApiKey as authorization

Having trouble using an ApiKey for authorising the ServerEventsClient.

Things I tried:

Add authentication support to net serverevents client replacing the provider with apikey and passing the apikey as the userName.

_serverEventsClient.ServiceClient.AddHeader("Authorization", "Bearer " + apiKey);

_serverEventsClient.ServiceClient.SetCredentials(apiKey, null);

But none of the above three seems to authorize.

The ServerEventsClient.ServiceClient only shared Cookies with the Service Client so will only work for Cookie Based Authentication Sessions. To customize the connection to the SSE /event-stream you can use the EventStreamRequestFilter:

new ServerEventsClient(...) {
    EventStreamRequestFilter = req => req.AddBearerToken(jwt)
}

The answer also shows an alternative to use the new ResolveStreamUrl to append the API Key to the QueryString but this requires that the ApiKeyAuthProvider is configured to accept API keys on the QueryString, e.g:

new ApiKeyAuthProvider {
     AllowInHttpParams = true
}
1 Like

OK! Working this one!