auth.go 3.0 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. "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. // Implements a basic Basic HTTP Authorization. It takes as arguments a map[string]string where
  27. // the key is the user name and the value is the password, as well as the name of the Realm
  28. // (see http://tools.ietf.org/html/rfc2617#section-1.2)
  29. func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {
  30. if realm == "" {
  31. realm = "Authorization Required"
  32. }
  33. realm = fmt.Sprintf("Basic realm=\"%s\"", realm)
  34. pairs := processAccounts(accounts)
  35. return func(c *Context) {
  36. // Search user in the slice of allowed credentials
  37. user, ok := searchCredential(pairs, c.Request.Header.Get("Authorization"))
  38. if !ok {
  39. // Credentials doesn't match, we return 401 Unauthorized and abort request.
  40. c.Writer.Header().Set("WWW-Authenticate", 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. 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. 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. }