ApiKey authorization with Encrypted Messaging

Hi there,

I’ve set up ApiKey authentication by following the guide: http://docs.servicestack.net/api-key-authprovider

It works fine, when I construct the client as follows:

        var baseUrl = "http://encryptedmessaging.com:8088";
        var apiKey = "vMz2g6CxtZi2cnqG3Da-CZg5bl_d7E_T";

        var client = new JsonServiceClient(baseUrl)
        {
            Credentials = new NetworkCredential(apiKey,"")
        };

        var authResponse = client.Send(new Authenticate());

With an encrypted client however, this the above does not work:

        string publicKeyXml = client.Get(new GetPublicKey());

        IEncryptedClient encryptedClient = client.GetEncryptedClient(publicKeyXml);

        var authResponse = client.Send(new Authenticate());

Returns ‘Invalid EncryptedMessage’ when Credentials = new NetworkCredential(apiKey,"") is set on the client. Not setting the Credentials and calling Authenticate returns Unauthorized (of course because I did not set the API key anywayre).

Question:

How to set the API Key in the Authenticate object, in order for Encrypted Messaging to work with API Keys?

I’ve tried

        var authResponse = encryptedClient.Send(new Authenticate
        {
            provider = "apikey",
            UserName = apiKey,
            Password = ""
        });

and am getting ‘Unauthorized’ back.

Thanks in advance

1 Like

Have your Request DTOs implement IHasBearerToken and use the BearerToken property, e.g:

public class Secure : IHasBearerToken
{
    public string BearerToken { get; set; }
    public string Name { get; set; }
}

IEncryptedClient encryptedClient = client.GetEncryptedClient(publicKey);
var response = encryptedClient.Get(new Secure { BearerToken = apiKey, Name = "World" });

Which can also be populated on the encryptedClient where it will automatically populate the BearerToken property in each Request DTO, e.g:

encryptedClient.BearerToken = apiKey;

var response = encryptedClient.Get(new Secure { Name = "World" });
1 Like

That solved the issue. Thanks!

1 Like