Authenticating with an NKey
The 2.0 version of NATS server introduces a new challenge response authentication option. This challenge response is based on a wrapper we call NKeys which uses Ed25519 signing. The server can use these keys in several ways for authentication. The simplest is for the server to be configured with a list of known public keys and for the clients to respond to the challenge by signing it with its private key. This challenge-response insures security by insuring that the client has the private key, but also protects the private key from the server which never has to actually see it.
Handling challenge response may require more than just a setting in the connection options, depending on the client library.
opt, err := nats.NkeyOptionFromSeed("seed.txt")
if err != nil {
log.Fatal(err)
}
nc, err := nats.Connect("localhost", opt)
if err != nil {
log.Fatal(err)
}
defer nc.Close()
// Do something with the connection
NKey theNKey = NKey.createUser(null); // really should load from somewhere
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();
Connection nc = Nats.connect(options);
// Do something with the connection
nc.close();