ghttp_request_auth.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package ghttp
  7. import (
  8. "fmt"
  9. "net/http"
  10. "strings"
  11. "github.com/gogf/gf/encoding/gbase64"
  12. )
  13. // BasicAuth enables the http basic authentication feature with given passport and password
  14. // and asks client for authentication. It returns true if authentication success, else returns
  15. // false if failure.
  16. func (r *Request) BasicAuth(user, pass string, tips ...string) bool {
  17. auth := r.Header.Get("Authorization")
  18. if auth == "" {
  19. r.setBasicAuth(tips...)
  20. return false
  21. }
  22. authArray := strings.SplitN(auth, " ", 2)
  23. if len(authArray) != 2 {
  24. r.Response.WriteStatus(http.StatusForbidden)
  25. return false
  26. }
  27. switch authArray[0] {
  28. case "Basic":
  29. authBytes, err := gbase64.DecodeString(authArray[1])
  30. if err != nil {
  31. r.Response.WriteStatus(http.StatusForbidden, err.Error())
  32. return false
  33. }
  34. authArray := strings.SplitN(string(authBytes), ":", 2)
  35. if len(authArray) != 2 {
  36. r.Response.WriteStatus(http.StatusForbidden)
  37. return false
  38. }
  39. if authArray[0] != user || authArray[1] != pass {
  40. r.setBasicAuth(tips...)
  41. return false
  42. }
  43. return true
  44. default:
  45. r.Response.WriteStatus(http.StatusForbidden)
  46. return false
  47. }
  48. }
  49. // setBasicAuth sets the http basic authentication tips.
  50. func (r *Request) setBasicAuth(tips ...string) {
  51. realm := ""
  52. if len(tips) > 0 && tips[0] != "" {
  53. realm = tips[0]
  54. } else {
  55. realm = "Need Login"
  56. }
  57. r.Response.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm))
  58. r.Response.WriteHeader(http.StatusUnauthorized)
  59. }