Authenticating with an NKey

    Handling challenge response may require more than just a setting in the connection options, depending on the client library.

    Java

    1. Options options = new Options.Builder().
    2. server("nats://localhost:4222").
    3. authHandler(new AuthHandler(){
    4. public char[] getID() {
    5. try {
    6. return theNKey.getPublicKey();
    7. } catch (GeneralSecurityException|IOException|NullPointerException ex) {
    8. return null;
    9. }
    10. }
    11. public byte[] sign(byte[] nonce) {
    12. try {
    13. return theNKey.sign(nonce);
    14. } catch (GeneralSecurityException|IOException|NullPointerException ex) {
    15. return null;
    16. }
    17. }
    18. public char[] getJWT() {
    19. return null;
    20. }
    21. }).
    22. build();
    23. // Do something with the connection
    24. nc.close();

    Python

    1. nc = NATS()
    2. async def error_cb(e):
    3. print("Error:", e)
    4. await nc.connect("nats://localhost:4222",
    5. nkeys_seed="./path/to/nkeys/user.nk",
    6. error_cb=error_cb,
    7. )
    8. # Do something with the connection
    9. await nc.close()

    C

    1. static natsStatus
    2. sigHandler(
    3. char **customErrTxt,
    4. unsigned char **signature,
    5. int *signatureLength,
    6. const char *nonce,
    7. void *closure)
    8. {
    9. // returned as `signatureLength`.
    10. // If an error occurs the user can return specific error text through
    11. // `customErrTxt`. The library will free this pointer.
    12. return NATS_OK;
    13. }
    14. (...)
    15. natsConnection *conn = NULL;
    16. natsOptions *opts = NULL;
    17. natsStatus s = NATS_OK;
    18. const char *pubKey = "my public key......";
    19. s = natsOptions_Create(&opts);
    20. if (s == NATS_OK)
    21. s = natsOptions_SetNKey(opts, pubKey, sigHandler, NULL);
    22. if (s == NATS_OK)
    23. s = natsConnection_Connect(&conn, opts);
    24. (...)
    25. // Destroy objects that were created
    26. natsConnection_Destroy(conn);