Go语言HTTP Basic Authorization实现认证登录

参考来源: https://www.jianshu.com/p/a09f1402c285
本文是以上大佬补充版本以及记录

在go语言中的Basic Authorization是一种基础的认证方式,
一般我们都不会使用这种认证方式,由于过于简单,
但是在prometheus中正好使用了该认证方法来进行我们客户端的metrics加密

  • prometheus.yaml配置文件

# 部分截取
  - job_name:  web 
    metrics_path: /metrics
    static_configs:
    - targets: [ 192.168.101.2 ]
    scheme: https                # 默认不开启https认证,需要使用https则配置该参数
    basic_auth:
      username: admin
      password: admin123

  • Basic Authorization通过中间件来实现.以下是两种handler注册时使用中间件

1. http.Handle

  // 结合prometheus一起使用
func main() {
    /*
            自定义registry(默认prometheus注册的registry不适用时)
        */
    registry := prometheus.NewRegistry()

    // 注册指标
    registry.MustRegister(errorLog.NewLogsCollect(lib.DirectoryList()))
    registry.MustRegister(service.NewGamesCollect())

    http.Handle("/metrics", baseAuth(promhttp.HandlerFor(registry, promhttp.HandlerOpts{Registry: registry})))
    http.ListenAndServe(":8050", nil)
}


/*中间件密码认证*/
func baseAuth(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        username, password, ok := r.BasicAuth()
        // fmt.Println(username, password, "----->")
        if !ok {
            AuthFailed(w, "401 Unauthorized!")
            return
        }
        if username != "admin" || password != "admin123" {
            AuthFailed(w, "401 Password error!")
            return
        }
        h.ServeHTTP(w, r)
    })
}

/*认证失败*/
func AuthFailed(w http.ResponseWriter, msg string) {
    w.Header().Set("WWW-Authenticate", `Basic realm="My METRICS"`)
    http.Error(w, msg, http.StatusUnauthorized)
}

2. http.HandleFunc

func main() {
    newPrometheus := NewPrometheus()
    http.HandleFunc("/metrics", BaseAuth(newPrometheus.Handler))

    http.ListenAndServe(":8050", nil)
}

type Prometheus struct {
    registry *prometheus.Registry
}

func NewPrometheus() *Prometheus {
    // 自定义registry
    registry := prometheus.NewRegistry()

    // 注册指标
    registry.MustRegister(errorLog.NewLogsCollect(lib.DirectoryList()))
    registry.MustRegister(service.NewGamesCollect())
    return &Prometheus{
        registry: registry,
    }
}

func (p *Prometheus) Handler(w http.ResponseWriter, r *http.Request) {
    handler := promhttp.HandlerFor(p.registry, promhttp.HandlerOpts{Registry: p.registry})
    handler.ServeHTTP(w, r)
}

func BaseAuth(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {
        username, password, ok := r.BasicAuth()
        fmt.Println(username, password, "----->")
        if !ok {
            AuthFailed(w, "401 Unauthorized!")
            return
        }
        if username != "admin" || password != "admin123" {
            AuthFailed(w, "401 Password error!")
            return
        }
        f(w, r)
    }
}

func AuthFailed(w http.ResponseWriter, msg string) {
    w.Header().Set("WWW-Authenticate", `Basic realm="My METRICS"`)
    w.WriteHeader(401)
    w.Write([]byte(msg))
}

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容