auth_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. "encoding/base64"
  7. "net/http"
  8. "net/http/httptest"
  9. "testing"
  10. )
  11. func TestBasicAuthSucceed(t *testing.T) {
  12. req, _ := http.NewRequest("GET", "/login", nil)
  13. w := httptest.NewRecorder()
  14. r := New()
  15. accounts := Accounts{"admin": "password"}
  16. r.Use(BasicAuth(accounts))
  17. r.GET("/login", func(c *Context) {
  18. c.String(200, "autorized")
  19. })
  20. req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))
  21. r.ServeHTTP(w, req)
  22. if w.Code != 200 {
  23. t.Errorf("Response code should be Ok, was: %s", w.Code)
  24. }
  25. bodyAsString := w.Body.String()
  26. if bodyAsString != "autorized" {
  27. t.Errorf("Response body should be `autorized`, was %s", bodyAsString)
  28. }
  29. }
  30. func TestBasicAuth401(t *testing.T) {
  31. req, _ := http.NewRequest("GET", "/login", nil)
  32. w := httptest.NewRecorder()
  33. r := New()
  34. accounts := Accounts{"foo": "bar"}
  35. r.Use(BasicAuth(accounts))
  36. r.GET("/login", func(c *Context) {
  37. c.String(200, "autorized")
  38. })
  39. req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))
  40. r.ServeHTTP(w, req)
  41. if w.Code != 401 {
  42. t.Errorf("Response code should be Not autorized, was: %s", w.Code)
  43. }
  44. if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"Authorization Required\"" {
  45. t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type"))
  46. }
  47. }
  48. func TestBasicAuth401WithCustomRealm(t *testing.T) {
  49. req, _ := http.NewRequest("GET", "/login", nil)
  50. w := httptest.NewRecorder()
  51. r := New()
  52. accounts := Accounts{"foo": "bar"}
  53. r.Use(BasicAuthForRealm(accounts, "My Custom Realm"))
  54. r.GET("/login", func(c *Context) {
  55. c.String(200, "autorized")
  56. })
  57. req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))
  58. r.ServeHTTP(w, req)
  59. if w.Code != 401 {
  60. t.Errorf("Response code should be Not autorized, was: %s", w.Code)
  61. }
  62. if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"My Custom Realm\"" {
  63. t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type"))
  64. }
  65. }