auth_test.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package gin
  2. import (
  3. "encoding/base64"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. )
  8. func TestBasicAuthSucceed(t *testing.T) {
  9. req, _ := http.NewRequest("GET", "/login", nil)
  10. w := httptest.NewRecorder()
  11. r := New()
  12. accounts := Accounts{"admin": "password"}
  13. r.Use(BasicAuth(accounts))
  14. r.GET("/login", func(c *Context) {
  15. c.String(200, "autorized")
  16. })
  17. req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))
  18. r.ServeHTTP(w, req)
  19. if w.Code != 200 {
  20. t.Errorf("Response code should be Ok, was: %s", w.Code)
  21. }
  22. bodyAsString := w.Body.String()
  23. if bodyAsString != "autorized" {
  24. t.Errorf("Response body should be `autorized`, was %s", bodyAsString)
  25. }
  26. }
  27. func TestBasicAuth401(t *testing.T) {
  28. req, _ := http.NewRequest("GET", "/login", nil)
  29. w := httptest.NewRecorder()
  30. r := New()
  31. accounts := Accounts{"foo": "bar"}
  32. r.Use(BasicAuth(accounts))
  33. r.GET("/login", func(c *Context) {
  34. c.String(200, "autorized")
  35. })
  36. req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))
  37. r.ServeHTTP(w, req)
  38. if w.Code != 401 {
  39. t.Errorf("Response code should be Not autorized, was: %s", w.Code)
  40. }
  41. if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"Authorization Required\"" {
  42. t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type"))
  43. }
  44. }