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:
58
middleware/auth_test.go
Normal file
58
middleware/auth_test.go
Normal 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")
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user