Authenticating with a Token
For this example, start the server using:
The code uses localhost:4222 so that you can start the server on your machine to try them out.
{% tabs %} {% tab title=”Go” %}
nc, 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
{% endtab %}
{% tab title=”Java” %}
Options options = new Options.Builder().
server("nats://localhost:4222").
token("mytoken"). // Set a token
build();
Connection nc = Nats.connect(options);
// Do something with the connection
{% endtab %}
{% tab title=”JavaScript” %}
const nc = await connect({
token: "aToK3n",
});
{% endtab %}
{% tab title=”Python” %}
{% tab title=”Ruby” %}
NATS.start(token: "mytoken") do |nc|
puts "Connected using token"
end
{% endtab %}
{% tab title=”C” %}
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);
(...)
natsConnection_Destroy(conn);
natsOptions_Destroy(opts);
{% endtab %} {% endtabs %}
Connecting with a Token in the URL
Some client libraries will allow you to pass the token as part of the server URL using the form:
Again, once you construct this URL you can connect as if this was a normal URL.
{% tabs %} {% tab title=”Go” %}
// Token in URL
nc, err := nats.Connect("mytoken@localhost")
if err != nil {
log.Fatal(err)
}
defer nc.Close()
// Do something with the connection
{% endtab %}
{% endtab %}
{% tab title=”JavaScript” %}
// JavaScript doesn't support tokens in urls use the `token` option
{% endtab %}
{% tab title=”Python” %}
nc = NATS()
await nc.connect(servers=["nats://mytoken@demo.nats.io:4222"])
# Do something with the connection.
{% endtab %}
{% tab title=”Ruby” %}
NATS.start("mytoken@127.0.0.1:4222") do |nc|
end
{% endtab %}
{% tab title=”C” %}
{% endtab %} {% endtabs %}