1
0
mirror of https://github.com/labstack/echo.git synced 2025-06-25 00:47:01 +02:00

Adding http basic authentication middleware

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2015-05-11 15:43:54 -07:00
parent 8ace8e2143
commit 69a97671ad
4 changed files with 125 additions and 0 deletions

58
middleware/auth_test.go Normal file
View File

@ -0,0 +1,58 @@
package middleware
import (
"encoding/base64"
"github.com/labstack/echo"
"net/http"
"net/http/httptest"
"testing"
)
func TestBasicAuth(t *testing.T) {
req, _ := http.NewRequest(echo.POST, "/", nil)
res := &echo.Response{Writer: httptest.NewRecorder()}
c := echo.NewContext(req, res, echo.New())
fn := func(u, p string) bool {
if u == "joe" && p == "secret" {
return true
}
return false
}
b := BasicAuth(fn)
//-------------------
// Valid credentials
//-------------------
auth := Basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))
req.Header.Set(echo.Authorization, auth)
if b(c) != nil {
t.Error("basic auth should pass")
}
// Case insensitive
auth = "basic " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))
req.Header.Set(echo.Authorization, auth)
if b(c) != nil {
t.Error("basic auth should ignore case and pass")
}
//---------------------
// Invalid credentials
//---------------------
auth = Basic + " " + base64.StdEncoding.EncodeToString([]byte(" joe: secret"))
req.Header.Set(echo.Authorization, auth)
b = BasicAuth(fn)
if b(c) == nil {
t.Error("basic auth should fail")
}
// Invalid scheme
auth = "foo " + base64.StdEncoding.EncodeToString([]byte(" joe: secret"))
req.Header.Set(echo.Authorization, auth)
b = BasicAuth(fn)
if b(c) == nil {
t.Error("basic auth should fail for invalid scheme")
}
}