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” %}

    1. nc, err := nats.Connect("127.0.0.1", nats.Name("API Token Example"), nats.Token("mytoken"))
    2. if err != nil {
    3. log.Fatal(err)
    4. }
    5. defer nc.Close()
    6. // Do something with the connection

    {% endtab %}

    {% tab title=”Java” %}

    1. Options options = new Options.Builder().
    2. server("nats://localhost:4222").
    3. token("mytoken"). // Set a token
    4. build();
    5. Connection nc = Nats.connect(options);
    6. // Do something with the connection

    {% endtab %}

    {% tab title=”JavaScript” %}

    1. const nc = await connect({
    2. token: "aToK3n",
    3. });

    {% endtab %}

    {% tab title=”Python” %}

    {% tab title=”Ruby” %}

    1. NATS.start(token: "mytoken") do |nc|
    2. puts "Connected using token"
    3. end

    {% endtab %}

    {% tab title=”C” %}

    1. natsConnection *conn = NULL;
    2. natsOptions *opts = NULL;
    3. natsStatus s = NATS_OK;
    4. s = natsOptions_Create(&opts);
    5. if (s == NATS_OK)
    6. s = natsOptions_SetToken(opts, "mytoken");
    7. if (s == NATS_OK)
    8. s = natsConnection_Connect(&conn, opts);
    9. (...)
    10. natsConnection_Destroy(conn);
    11. 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” %}

    1. // Token in URL
    2. nc, err := nats.Connect("mytoken@localhost")
    3. if err != nil {
    4. log.Fatal(err)
    5. }
    6. defer nc.Close()
    7. // Do something with the connection

    {% endtab %}

    {% endtab %}

    {% tab title=”JavaScript” %}

    1. // JavaScript doesn't support tokens in urls use the `token` option

    {% endtab %}

    {% tab title=”Python” %}

    1. nc = NATS()
    2. await nc.connect(servers=["nats://mytoken@demo.nats.io:4222"])
    3. # Do something with the connection.

    {% endtab %}

    {% tab title=”Ruby” %}

    1. NATS.start("mytoken@127.0.0.1:4222") do |nc|
    2. end

    {% endtab %}

    {% tab title=”C” %}

    {% endtab %} {% endtabs %}