Ai
1 Star 0 Fork 1

flanche/echo

forked from guapian/echo 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
auth.go 1.30 KB
一键复制 编辑 原始数据 按行查看 历史
package middleware
import (
"encoding/base64"
"github.com/labstack/echo"
"net/http"
)
type (
AuthFunc func(string, string) bool
)
const (
Basic = "Basic"
)
// BasicAuth returns an HTTP basic authentication middleware. For valid credentials
// it calls the next handler in the chain.
// For invalid Authorization header it sends "404 - Bad Request" response.
// For invalid credentials, it sends "401 - Unauthorized" response.
func BasicAuth(fn AuthFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
auth := c.Request().Header.Get(echo.Authorization)
i := 0
code := http.StatusBadRequest
for ; i < len(auth); i++ {
c := auth[i]
// Ignore empty spaces
if c == ' ' {
continue
}
// Check scheme
if i < len(Basic) {
// Ignore case
if i == 0 {
if c != Basic[i] && c != 'b' {
break
}
} else {
if c != Basic[i] {
break
}
}
} else {
// Extract credentials
b, err := base64.StdEncoding.DecodeString(auth[i:])
if err != nil {
break
}
cred := string(b)
for i := 0; i < len(cred); i++ {
if cred[i] == ':' {
// Verify credentials
if fn(cred[:i], cred[i+1:]) {
return nil
}
code = http.StatusUnauthorized
break
}
}
}
}
return echo.NewHTTPError(code)
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/flanche/echo.git
git@gitee.com:flanche/echo.git
flanche
echo
echo
v0.0.15

搜索帮助