auth.go 2.7 KB

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