auth.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package gin
  5. import (
  6. "crypto/subtle"
  7. "encoding/base64"
  8. "errors"
  9. "fmt"
  10. "sort"
  11. )
  12. const (
  13. AuthUserKey = "user"
  14. )
  15. type (
  16. Accounts map[string]string
  17. authPair struct {
  18. Value string
  19. User string
  20. }
  21. authPairs []authPair
  22. )
  23. func (a authPairs) Len() int { return len(a) }
  24. func (a authPairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  25. func (a authPairs) Less(i, j int) bool { return a[i].Value < a[j].Value }
  26. func (a authPairs) searchCredential(auth string) (string, bool) {
  27. if len(auth) == 0 {
  28. return "", false
  29. }
  30. // Search user in the slice of allowed credentials
  31. r := sort.Search(len(a), func(i int) bool { return a[i].Value >= auth })
  32. if r < len(a) && secureCompare(a[r].Value, auth) {
  33. return a[r].User, true
  34. } else {
  35. return "", false
  36. }
  37. }
  38. // Implements a basic Basic HTTP Authorization. It takes as arguments a map[string]string where
  39. // the key is the user name and the value is the password, as well as the name of the Realm
  40. // (see http://tools.ietf.org/html/rfc2617#section-1.2)
  41. func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {
  42. if realm == "" {
  43. realm = "Authorization Required"
  44. }
  45. realm = fmt.Sprintf("Basic realm=\"%s\"", realm)
  46. pairs := processAccounts(accounts)
  47. return func(c *Context) {
  48. // Search user in the slice of allowed credentials
  49. user, ok := pairs.searchCredential(c.Request.Header.Get("Authorization"))
  50. if !ok {
  51. // Credentials doesn't match, we return 401 Unauthorized and abort request.
  52. c.Writer.Header().Set("WWW-Authenticate", realm)
  53. c.Fail(401, errors.New("Unauthorized"))
  54. } else {
  55. // user is allowed, set UserId to key "user" in this context, the userId can be read later using
  56. // c.Get(gin.AuthUserKey)
  57. c.Set(AuthUserKey, user)
  58. }
  59. }
  60. }
  61. // Implements a basic Basic HTTP Authorization. It takes as argument a map[string]string where
  62. // the key is the user name and the value is the password.
  63. func BasicAuth(accounts Accounts) HandlerFunc {
  64. return BasicAuthForRealm(accounts, "")
  65. }
  66. func processAccounts(accounts Accounts) authPairs {
  67. if len(accounts) == 0 {
  68. panic("Empty list of authorized credentials")
  69. }
  70. pairs := make(authPairs, 0, len(accounts))
  71. for user, password := range accounts {
  72. if len(user) == 0 {
  73. panic("User can not be empty")
  74. }
  75. value := authorizationHeader(user, password)
  76. pairs = append(pairs, authPair{
  77. Value: value,
  78. User: user,
  79. })
  80. }
  81. // We have to sort the credentials in order to use bsearch later.
  82. sort.Sort(pairs)
  83. return pairs
  84. }
  85. func authorizationHeader(user, password string) string {
  86. base := user + ":" + password
  87. return "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
  88. }
  89. func secureCompare(given, actual string) bool {
  90. if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
  91. return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
  92. } else {
  93. /* Securely compare actual to itself to keep constant time, but always return false */
  94. return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false
  95. }
  96. }