Skip to content

Commit

Permalink
Add token support, fixes #79
Browse files Browse the repository at this point in the history
  • Loading branch information
derekcollison committed Jan 20, 2016
1 parent 6c5b8c0 commit f65d2e3
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
15 changes: 11 additions & 4 deletions nats.go
Expand Up @@ -266,6 +266,7 @@ type connectInfo struct {
Pedantic bool `json:"pedantic"`
User string `json:"user,omitempty"`
Pass string `json:"pass,omitempty"`
Token string `json:"auth_token,omitempty"`
TLS bool `json:"tls_required"`
Name string `json:"name"`
Lang string `json:"lang"`
Expand Down Expand Up @@ -890,13 +891,19 @@ func (nc *Conn) sendProto(proto string) {
// applicable. The lock is assumed to be held upon entering.
func (nc *Conn) connectProto() (string, error) {
o := nc.Opts
var user, pass string
var user, pass, token string
u := nc.url.User
if u != nil {
user = u.Username()
pass, _ = u.Password()
// if no password, assume username is authToken
if _, ok := u.Password(); !ok {
token = u.Username()
} else {
user = u.Username()
pass, _ = u.Password()
}
}
cinfo := connectInfo{o.Verbose, o.Pedantic, user, pass,
cinfo := connectInfo{o.Verbose, o.Pedantic,
user, pass, token,
o.Secure, o.Name, LangString, Version}
b, err := json.Marshal(cinfo)
if err != nil {
Expand Down
26 changes: 25 additions & 1 deletion test/auth_test.go
@@ -1,6 +1,7 @@
package test

import (
"fmt"
"sync/atomic"
"testing"
"time"
Expand Down Expand Up @@ -28,7 +29,7 @@ func TestAuth(t *testing.T) {

nc, err := nats.Connect("nats://derek:foo@localhost:8232")
if err != nil {
t.Fatal("Should have connected successfully")
t.Fatal("Should have connected successfully with a token")
}
nc.Close()
}
Expand Down Expand Up @@ -122,3 +123,26 @@ func TestAuthFailAllowReconnect(t *testing.T) {
t.Fatalf("Should have reconnected to %s, reconnected to %s instead", servers[2], nc.ConnectedUrl())
}
}

func TestTokenAuth(t *testing.T) {
s := RunServerOnPort(8232)

secret := "S3Cr3T0k3n!"
// Auth is pluggable, so need to set here..
auth := &auth.Token{Token: secret}
s.SetAuthMethod(auth)

defer s.Shutdown()

_, err := nats.Connect("nats://localhost:8232")
if err == nil {
t.Fatal("Should have received an error while trying to connect")
}

tokenUrl := fmt.Sprintf("nats://%s@localhost:8232", secret)
nc, err := nats.Connect(tokenUrl)
if err != nil {
t.Fatal("Should have connected successfully")
}
nc.Close()
}

0 comments on commit f65d2e3

Please sign in to comment.