Authenticating with an NKey
Handling challenge response may require more than just a setting in the connection options, depending on the client library.
Java
Options options = new Options.Builder().
server("nats://localhost:4222").
authHandler(new AuthHandler(){
public char[] getID() {
try {
return theNKey.getPublicKey();
} catch (GeneralSecurityException|IOException|NullPointerException ex) {
return null;
}
}
public byte[] sign(byte[] nonce) {
try {
return theNKey.sign(nonce);
} catch (GeneralSecurityException|IOException|NullPointerException ex) {
return null;
}
}
public char[] getJWT() {
return null;
}
}).
build();
// Do something with the connection
nc.close();
Python
nc = NATS()
async def error_cb(e):
print("Error:", e)
await nc.connect("nats://localhost:4222",
nkeys_seed="./path/to/nkeys/user.nk",
error_cb=error_cb,
)
# Do something with the connection
await nc.close()
C
static natsStatus
sigHandler(
char **customErrTxt,
unsigned char **signature,
int *signatureLength,
const char *nonce,
void *closure)
{
// returned as `signatureLength`.
// If an error occurs the user can return specific error text through
// `customErrTxt`. The library will free this pointer.
return NATS_OK;
}
(...)
natsConnection *conn = NULL;
natsOptions *opts = NULL;
natsStatus s = NATS_OK;
const char *pubKey = "my public key......";
s = natsOptions_Create(&opts);
if (s == NATS_OK)
s = natsOptions_SetNKey(opts, pubKey, sigHandler, NULL);
if (s == NATS_OK)
s = natsConnection_Connect(&conn, opts);
(...)
// Destroy objects that were created
natsConnection_Destroy(conn);