golang用户认证
生活随笔
收集整理的這篇文章主要介紹了
golang用户认证
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在開發Web應用過程中,用戶認證是開發者經常遇到的問題,用戶登錄、注冊、登出等操作,而一般認證也分為三個方面的認證
- HTTP Basic和 HTTP Digest認證
- 第三方集成認證:QQ、微博、豆瓣、OPENID、google、github、facebook和twitter等
- 自定義的用戶登錄、注冊、登出,一般都是基于session、cookie認證
beego目前沒有針對這三種方式進行任何形式的集成,但是可以充分的利用第三方開源庫來實現上面的三種方式的用戶認證,不過后續beego會對前面兩種認證逐步集成。
HTTP Basic和 HTTP Digest認證
這兩個認證是一些應用采用的比較簡單的認證,目前已經有開源的第三方庫支持這兩個認證:
github.com/abbot/go-http-auth下面代碼演示了如何把這個庫引入beego中從而實現認證:
package controllersimport ("github.com/abbot/go-http-auth""github.com/astaxie/beego" )func Secret(user, realm string) string {if user == "john" {// password is "hello"return "$1$dlPL2MqE$oQmn16q49SqdmhenQuNgs1"}return "" }type MainController struct {beego.Controller }func (this *MainController) Prepare() {a := auth.NewBasicAuthenticator("example.com", Secret)if username := a.CheckAuth(this.Ctx.Request); username == "" {a.RequireAuth(this.Ctx.ResponseWriter, this.Ctx.Request)} }func (this *MainController) Get() {this.Data["Username"] = "astaxie"this.Data["Email"] = "astaxie@gmail.com"this.TplNames = "index.tpl" }上面代碼利用了beego的prepare函數,在執行正常邏輯之前調用了認證函數,這樣就非常簡單的實現了http auth,digest的認證也是同樣的原理。
oauth和oauth2的認證
oauth和oauth2是目前比較流行的兩種認證方式,還好第三方有一個庫實現了這個認證,但是是國外實現的,并沒有QQ、微博之類的國內應用認證集成:
github.com/bradrydzewski/go.auth下面代碼演示了如何把該庫引入beego中從而實現oauth的認證,這里以github為例演示:
添加兩條路由
beego.RegisterController("/auth/login", &controllers.GithubController{}) beego.RegisterController("/mainpage", &controllers.PageController{})然后我們處理GithubController登陸的頁面:
package controllersimport ("github.com/astaxie/beego""github.com/bradrydzewski/go.auth" )const (githubClientKey = "a0864ea791ce7e7bd0df"githubSecretKey = "a0ec09a647a688a64a28f6190b5a0d2705df56ca" )type GithubController struct {beego.Controller }func (this *GithubController) Get() {// set the auth parametersauth.Config.CookieSecret = []byte("7H9xiimk2QdTdYI7rDddfJeV")auth.Config.LoginSuccessRedirect = "/mainpage"auth.Config.CookieSecure = falsegithubHandler := auth.Github(githubClientKey, githubSecretKey)githubHandler.ServeHTTP(this.Ctx.ResponseWriter, this.Ctx.Request) }處理登陸成功之后的頁面
package controllersimport ("github.com/astaxie/beego""github.com/bradrydzewski/go.auth""net/http""net/url" )type PageController struct {beego.Controller }func (this *PageController) Get() {// set the auth parametersauth.Config.CookieSecret = []byte("7H9xiimk2QdTdYI7rDddfJeV")auth.Config.LoginSuccessRedirect = "/mainpage"auth.Config.CookieSecure = falseuser, err := auth.GetUserCookie(this.Ctx.Request)//if no active user session then authorize userif err != nil || user.Id() == "" {http.Redirect(this.Ctx.ResponseWriter, this.Ctx.Request, auth.Config.LoginRedirect, http.StatusSeeOther)return}//else, add the user to the URL and continuethis.Ctx.Request.URL.User = url.User(user.Id())this.Data["pic"] = user.Picture()this.Data["id"] = user.Id()this.Data["name"] = user.Name()this.TplNames = "home.tpl" }總結
以上是生活随笔為你收集整理的golang用户认证的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: golang表单及验证支持
- 下一篇: golang多语言支持