码迷,mamicode.com
首页 > 其他好文 > 详细

BasicAuth

时间:2019-12-19 23:37:27      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:tag   get   cat   write   www   play   ted   ati   set   

Go实现

在头里设置WWW-Authenticate

返回401

func (webhandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
    writer.Header().Set("WWW-Authenticate", `Basic realm="您必须输入用户名和密码"`)
    writer.WriteHeader(http.StatusUnauthorized)
}

技术图片

func (webhandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
    auth := request.Header.Get("Authorization") //获取Basic base64加密后的字段
    if auth == "" {
        writer.Header().Set("WWW-Authenticate", `Basic realm="您必须输入用户名和密码"`)
        writer.WriteHeader(http.StatusUnauthorized)
        return
    }
    auth_list := strings.Split(auth, " ")
    if len(auth_list) == 2 && auth_list[0] == "Basic"{
        res,err := base64.StdEncoding.DecodeString(auth_list[1])
        if err == nil && string(res) == "shenyi:123" { //输入的用户名和密码会用:隔开
            writer.Write([]byte("<h1>web1</h1>"))
            return
        }
    }
    writer.Write([]byte("用户名密码错误"))
}




BasicAuth

标签:tag   get   cat   write   www   play   ted   ati   set   

原文地址:https://www.cnblogs.com/hualou/p/12070706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!