auth.go 2.7 KB

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