@@ -131,6 +131,7 @@ var (
131
131
ErrNkeysNotSupported = errors .New ("nats: nkeys not supported by the server" )
132
132
ErrStaleConnection = errors .New ("nats: " + STALE_CONNECTION )
133
133
ErrTokenAlreadySet = errors .New ("nats: token and token handler both set" )
134
+ ErrUserInfoAlreadySet = errors .New ("nats: user info and user info handler both set" )
134
135
ErrMsgNotBound = errors .New ("nats: message is not bound to subscription/connection" )
135
136
ErrMsgNoReply = errors .New ("nats: message does not have a reply" )
136
137
ErrClientIPNotSupported = errors .New ("nats: client IP not supported by this server" )
@@ -230,6 +231,9 @@ type SignatureHandler func([]byte) ([]byte, error)
230
231
// AuthTokenHandler is used to generate a new token.
231
232
type AuthTokenHandler func () string
232
233
234
+ // AuthUserInfoHandler is used to fetch username and password.
235
+ type AuthUserInfoHandler func () (string , string )
236
+
233
237
// ReconnectDelayHandler is used to get from the user the desired
234
238
// delay the library should pause before attempting to reconnect
235
239
// again. Note that this is invoked after the library tried the
@@ -443,6 +447,10 @@ type Options struct {
443
447
// Password sets the password to be used when connecting to a server.
444
448
Password string
445
449
450
+ // UserInfoHandler designates the function used to fetch the username and
451
+ // password to be used when connecting to a server.
452
+ UserInfoHandler AuthUserInfoHandler
453
+
446
454
// Token sets the token to be used when connecting to a server.
447
455
Token string
448
456
@@ -1166,6 +1174,15 @@ func UserInfo(user, password string) Option {
1166
1174
}
1167
1175
}
1168
1176
1177
+ // UserInfoHandler is an Option to set the user info handler to use when a
1178
+ // username and password is not otherwise specified.
1179
+ func UserInfoHandler (cb AuthUserInfoHandler ) Option {
1180
+ return func (o * Options ) error {
1181
+ o .UserInfoHandler = cb
1182
+ return nil
1183
+ }
1184
+ }
1185
+
1169
1186
// Token is an Option to set the token to use
1170
1187
// when a token is not included directly in the URLs
1171
1188
// and when a token handler is not provided.
@@ -2557,6 +2574,13 @@ func (nc *Conn) connectProto() (string, error) {
2557
2574
token = nc .Opts .TokenHandler ()
2558
2575
}
2559
2576
2577
+ if nc .Opts .UserInfoHandler != nil {
2578
+ if user != _EMPTY_ || pass != _EMPTY_ {
2579
+ return _EMPTY_ , ErrUserInfoAlreadySet
2580
+ }
2581
+ user , pass = nc .Opts .UserInfoHandler ()
2582
+ }
2583
+
2560
2584
// If our server does not support headers then we can't do them or no responders.
2561
2585
hdrs := nc .info .Headers
2562
2586
cinfo := connectInfo {o .Verbose , o .Pedantic , ujwt , nkey , sig , user , pass , token ,
0 commit comments