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.

    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

    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
    7. nc.close();

    JavaScript

    1. let nc = NATS.connect({url: `nats://127.0.0.1:${port}`, token: "mytoken!"});
    1. nc = NATS()
    2. await nc.connect(servers=["nats://demo.nats.io:4222"], token="mytoken")
    3. # Do something with the connection.

    Ruby

    TypeScript

      C

      1. natsConnection *conn = NULL;
      2. natsStatus s = NATS_OK;
      3. s = natsOptions_Create(&opts);
      4. if (s == NATS_OK)
      5. s = natsOptions_SetToken(opts, "mytoken");
      6. if (s == NATS_OK)
      7. s = natsConnection_Connect(&conn, opts);
      8. (...)
      9. // Destroy objects that were created
      10. natsConnection_Destroy(conn);
      11. natsOptions_Destroy(opts);

      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:

      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

      Java

      1. Connection nc = Nats.connect("nats://mytoken@localhost:4222");//Token in URL
      2. nc.close();

      JavaScript

      Python

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

      Ruby

      1. NATS.start("mytoken@127.0.0.1:4222") do |nc|
      2. puts "Connected using token!"
      3. end
      1. let url = `nats://:mytoken@127.0.0.1:${port}`;
      2. let nc = await connect({url: url});

      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_SetURL(opts, "nats://mytoken@127.0.0.1:4222");
      7. if (s == NATS_OK)
      8. s = natsConnection_Connect(&conn, opts);
      9. (...)
      10. // Destroy objects that were created
      11. natsOptions_Destroy(opts);