Tokens are basically random strings, much like a password, and can provide a simple authentication mechanism in some situations. However, tokens are only as safe as they are secret so other authentication schemes can provide more security in large installations. It is highly recommended to use one of the other NATS authentication mechanisms.
For this example, start the server using:
> nats-server --auth mytoken
The code uses localhost:4222 so that you can start the server on your machine to try them out.
// Set a tokennc, err := nats.Connect("127.0.0.1", nats.Name("API Token Example"), nats.Token("mytoken"))if err != nil {log.Fatal(err)}defer nc.Close()​// Do something with the connection
Options options = new Options.Builder().server("nats://localhost:4222").token("mytoken"). // Set a tokenbuild();Connection nc = Nats.connect(options);​// Do something with the connection​nc.close();
let nc = NATS.connect({url: `nats://127.0.0.1:${port}`, token: "mytoken!"});
nc = NATS()​await nc.connect(servers=["nats://demo.nats.io:4222"], token="mytoken")​# Do something with the connection.
NATS.start(token: "mytoken") do |nc|puts "Connected using token"end
let nc = await connect({url: server.nats, token: "mytoken"});
natsConnection *conn = NULL;natsOptions *opts = NULL;natsStatus s = NATS_OK;​s = natsOptions_Create(&opts);if (s == NATS_OK)s = natsOptions_SetToken(opts, "mytoken");if (s == NATS_OK)s = natsConnection_Connect(&conn, opts);​(...)​// Destroy objects that were creatednatsConnection_Destroy(conn);natsOptions_Destroy(opts);
Some client libraries will allow you to pass the token as part of the server URL using the form:
nats://token@server:port
Again, once you construct this URL you can connect as if this was a normal URL.
// Token in URLnc, err := nats.Connect("[email protected]")if err != nil {log.Fatal(err)}defer nc.Close()​// Do something with the connection
Connection nc = Nats.connect("nats://[email protected]:4222");//Token in URL​// Do something with the connection​nc.close();
let url = `nats://[email protected]:${port}`;let nc = NATS.connect({url: url});
nc = NATS()​await nc.connect(servers=["nats://[email protected]:4222"])​# Do something with the connection.
NATS.start("[email protected]:4222") do |nc|puts "Connected using token!"end
let url = `nats://:[email protected]:${port}`;let nc = await connect({url: url});
natsConnection *conn = NULL;natsOptions *opts = NULL;natsStatus s = NATS_OK;​s = natsOptions_Create(&opts);if (s == NATS_OK)s = natsOptions_SetURL(opts, "nats://[email protected]:4222");if (s == NATS_OK)s = natsConnection_Connect(&conn, opts);​(...)​// Destroy objects that were creatednatsConnection_Destroy(conn);natsOptions_Destroy(opts);