auth.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (c) 2012, Sean Treadway, SoundCloud Ltd.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Source code and contact info at http://github.com/streadway/amqp
  5. package amqp
  6. import (
  7. "fmt"
  8. )
  9. // Authentication interface provides a means for different SASL authentication
  10. // mechanisms to be used during connection tuning.
  11. type Authentication interface {
  12. Mechanism() string
  13. Response() string
  14. }
  15. // PlainAuth is a similar to Basic Auth in HTTP.
  16. type PlainAuth struct {
  17. Username string
  18. Password string
  19. }
  20. // Mechanism returns "PLAIN"
  21. func (auth *PlainAuth) Mechanism() string {
  22. return "PLAIN"
  23. }
  24. // Response returns the null character delimited encoding for the SASL PLAIN Mechanism.
  25. func (auth *PlainAuth) Response() string {
  26. return fmt.Sprintf("\000%s\000%s", auth.Username, auth.Password)
  27. }
  28. // AMQPlainAuth is similar to PlainAuth
  29. type AMQPlainAuth struct {
  30. Username string
  31. Password string
  32. }
  33. // Mechanism returns "AMQPLAIN"
  34. func (auth *AMQPlainAuth) Mechanism() string {
  35. return "AMQPLAIN"
  36. }
  37. // Response returns the null character delimited encoding for the SASL PLAIN Mechanism.
  38. func (auth *AMQPlainAuth) Response() string {
  39. return fmt.Sprintf("LOGIN:%sPASSWORD:%s", auth.Username, auth.Password)
  40. }
  41. // Finds the first mechanism preferred by the client that the server supports.
  42. func pickSASLMechanism(client []Authentication, serverMechanisms []string) (auth Authentication, ok bool) {
  43. for _, auth = range client {
  44. for _, mech := range serverMechanisms {
  45. if auth.Mechanism() == mech {
  46. return auth, true
  47. }
  48. }
  49. }
  50. return
  51. }