1 Star 0 Fork 0

天雨流芳 / go-micro-framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
basic.go 1.73 KB
一键复制 编辑 原始数据 按行查看 历史
天雨流芳 提交于 2024-03-29 17:26 . 基于gin的server
package strategy
import (
"encoding/base64"
"gitee.com/tylf2018/go-micro-framework/pkg/code"
"gitee.com/tylf2018/go-micro-framework/pkg/common/core"
"gitee.com/tylf2018/go-micro-framework/pkg/errors"
"strings"
"github.com/gin-gonic/gin"
)
// BasicStrategy defines Basic authentication strategy.
type BasicStrategy struct {
compare func(c *gin.Context, string, password string) bool
}
// NewBasicStrategy create basic strategy with compare function.
func NewBasicStrategy(compare func(c *gin.Context, username string, password string) bool) *BasicStrategy {
return &BasicStrategy{
compare: compare,
}
}
// AuthFunc defines basic strategy as the gin authentication middleware.
func (b BasicStrategy) AuthFunc() gin.HandlerFunc {
return func(c *gin.Context) {
// 从 Header 获取 Authorization 的值 以 空格 切割
auth := strings.SplitN(c.Request.Header.Get("Authorization"), " ", 2)
if len(auth) != 2 || auth[0] != "Basic" {
core.WriteResponse(
c,
errors.WithCode(code.ErrSignatureInvalid.Code(), "Authorization header format is wrong."),
nil,
)
c.Abort()
return
}
// 虽然是base64编码后发送 但是 base64也是明文传输 一般用于内部访问(因为快捷)
payload, _ := base64.StdEncoding.DecodeString(auth[1]) // 返回 base64 编码的 二进制数据
pair := strings.SplitN(string(payload), ":", 2) // 前面是用户名 后面是密码
// 核心验证逻辑 在 compare 方法中 验证 账号和密码是否正确 compare 需要注册进来
if len(pair) != 2 || !b.compare(c, pair[0], pair[1]) {
core.WriteResponse(
c,
errors.WithCode(code.ErrSignatureInvalid.Code(), "Authorization header format is wrong."),
nil,
)
c.Abort()
return
}
c.Next()
}
}
1
https://gitee.com/tylf2018/go-micro-framework.git
git@gitee.com:tylf2018/go-micro-framework.git
tylf2018
go-micro-framework
go-micro-framework
a23f37e8bd2b

搜索帮助

53164aa7 5694891 3bd8fe86 5694891