auth.go 3.1 KB

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