auth.go 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package gin
  2. import (
  3. "crypto/subtle"
  4. "encoding/base64"
  5. "errors"
  6. "sort"
  7. )
  8. const (
  9. AuthUserKey = "user"
  10. )
  11. type (
  12. BasicAuthPair struct {
  13. Code string
  14. User string
  15. }
  16. Account struct {
  17. User string
  18. Password string
  19. }
  20. Accounts []Account
  21. Pairs []BasicAuthPair
  22. )
  23. func (a Pairs) Len() int { return len(a) }
  24. func (a Pairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  25. func (a Pairs) Less(i, j int) bool { return a[i].Code < a[j].Code }
  26. func processCredentials(accounts Accounts) (Pairs, error) {
  27. if len(accounts) == 0 {
  28. return nil, errors.New("Empty list of authorized credentials.")
  29. }
  30. pairs := make(Pairs, 0, len(accounts))
  31. for _, account := range accounts {
  32. if len(account.User) == 0 || len(account.Password) == 0 {
  33. return nil, errors.New("User or password is empty")
  34. }
  35. base := account.User + ":" + account.Password
  36. code := "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
  37. pairs = append(pairs, BasicAuthPair{code, account.User})
  38. }
  39. // We have to sort the credentials in order to use bsearch later.
  40. sort.Sort(pairs)
  41. return pairs, nil
  42. }
  43. func secureCompare(given, actual string) bool {
  44. if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
  45. return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
  46. } else {
  47. /* Securely compare actual to itself to keep constant time, but always return false */
  48. return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false
  49. }
  50. }
  51. func searchCredential(pairs Pairs, auth string) string {
  52. if len(auth) == 0 {
  53. return ""
  54. }
  55. // Search user in the slice of allowed credentials
  56. r := sort.Search(len(pairs), func(i int) bool { return pairs[i].Code >= auth })
  57. if r < len(pairs) && secureCompare(pairs[r].Code, auth) {
  58. return pairs[r].User
  59. } else {
  60. return ""
  61. }
  62. }
  63. // Implements a basic Basic HTTP Authorization. It takes as argument a map[string]string where
  64. // the key is the user name and the value is the password.
  65. func BasicAuth(accounts Accounts) HandlerFunc {
  66. pairs, err := processCredentials(accounts)
  67. if err != nil {
  68. panic(err)
  69. }
  70. return func(c *Context) {
  71. // Search user in the slice of allowed credentials
  72. user := searchCredential(pairs, c.Req.Header.Get("Authorization"))
  73. if len(user) == 0 {
  74. // Credentials doesn't match, we return 401 Unauthorized and abort request.
  75. c.Writer.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
  76. c.Fail(401, errors.New("Unauthorized"))
  77. } else {
  78. // user is allowed, set UserId to key "user" in this context, the userId can be read later using
  79. // c.Get(gin.AuthUserKey)
  80. c.Set(AuthUserKey, user)
  81. }
  82. }
  83. }