API Key Auth and Authenticated Request via MQ

What is the recommend way to use API Key Auth with Authenticated Request via MQ?

As API Key Auth doesn’t persist a session (because it implements IAuthWithRequest) it’s not possible to use the normal technique of capturing the SessionId to pass with the MQ request.

I know it’s possible to set the PersistSession so a sessions are saved, but not saving them is the desired behaviour for HTTP requests.

I was hoping that by submitting a Authenticate request with RememberMe = true would result in a persisted session.

My current solution is to create a custom credentials provider which delegates to the API key provider to validate the key. When a persisted session is needed then an authenticate request must be made to get a SessionId.

var response = client.Post(new Authenticate {
    provider = "apikeycredentials".
    UserName = "apikey",
    RememberMe = true
});

Is there a way you can occasionally request a persisted session using just the API Key provider?

All the docs related to Authenticating via MQ is in the docs, i.e you’d need to include the API Key with the Request DTO and use it to simulate the MQ BasicRequest to populate it with the Headers it’s expecting to find the API Key in, e.g:

mqServer.RegisterHandler<AuthOnly>(m => {
    var req = new BasicRequest { Verb = HttpMethods.Post };
    req.Headers[HttpHeaders.Authorization] = "Bearer " + m.GetBody().ApiKey;
    var response = ExecuteMessage(m, req);
    return response;
});

You could also validate the API Key in your Service with something like:

public object Any(MqRequest request)
{
    var authRepo = (IManageApiKeys)AuthRepository;
    var apiKey = authRepo.GetApiKey(request.ApiKey);
    var validKey = apiKey != null && apiKey.CancelledDate == null && 
        (apiKey.ExpiryDate == null || DateTime.UtcNow <= apiKey.ExpiryDate.Value);
    if (!validKey)
        throw HttpError.Forbidden("Invalid ApiKey");
    var user = AuthRepository.GetUserAuth(apiKey.UserAuthId);
}

Keep in mind that MQ Requests are typically considered to be internal requests which normally bypass Global Request/Response Filters like Authentication, you need to annotate the [Authenticate] at the method level to enforce Authentication for MQ Requests.

1 Like