auth.go 2.5 KB

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