HTTP Basic Auth with Golang

左心房为你撑大大i 提交于 2019-12-10 23:33:57

问题


How do I implement basic auth with a Golang site? So that when someone visits a page they will be prompted by their browser with a login.


回答1:


In order to force a user to authenticate/make that basic auth prompt in the users browser appear you send the header WWW-Authenticate : Basic ream="mydomain"

So if you have a http.ResponseWriter called w, you can do

 w.Header().Set("WWW-Authenticate", `Basic realm="mydomain"`)

Which will cause the browser to open the prompt you're referring to.




回答2:


You could also use Echo's labstack project, which provides Basic Auth middleware:

e.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
    // check username and password for a match here
}))

Use the code above to protect any route groups with basic authentication.



来源:https://stackoverflow.com/questions/36187853/http-basic-auth-with-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!