<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Go 每日一庫(kù)之 goth

          共 4322字,需瀏覽 9分鐘

           ·

          2021-11-15 08:03

          簡(jiǎn)介

          當(dāng)前很多網(wǎng)站直接采用第三方認(rèn)證登錄,例如支付寶/微信/ Github 等。goth封裝了接入第三方認(rèn)證的方法,并且內(nèi)置實(shí)現(xiàn)了很多第三方認(rèn)證的實(shí)現(xiàn):

          圖中截取的只是goth支持的一部分,完整列表可在其GitHub 首頁(yè)查看。

          快速使用

          本文代碼使用 Go Modules。

          創(chuàng)建目錄并初始化:

          $ mkdir goth && cd goth
          $ go mod init github.com/darjun/go-daily-lib/goth

          安裝goth庫(kù):

          $ go get -u github.com/markbates/goth

          我們?cè)O(shè)計(jì)了兩個(gè)頁(yè)面,一個(gè)登錄頁(yè)面:

          //?login.tpl
          "/auth/github?provider=github">Login?With?GitHub

          點(diǎn)擊登錄鏈接會(huì)請(qǐng)求/auth/github?provider=github

          一個(gè)主界面:

          //?home.tpl

          "/logout/github">logout


          Name:?{{.Name}}?[{{.LastName}},?{{.FirstName}}]


          Email:?{{.Email}}


          NickName:?{{.NickName}}


          Location:?{{.Location}}


          AvatarURL:?{{.AvatarURL}}?"{{.AvatarURL}}">


          Description:?{{.Description}}


          UserID:?{{.UserID}}


          AccessToken:?{{.AccessToken}}


          ExpiresAt:?{{.ExpiresAt}}


          RefreshToken:?{{.RefreshToken}}


          顯示用戶的基本信息。

          同樣地,我們使用html/template標(biāo)準(zhǔn)模板庫(kù)來加載和管理頁(yè)面模板:

          var?(
          ??ptTemplate?*template.Template
          )

          func?init()?{
          ??ptTemplate?=?template.Must(template.New("").ParseGlob("tpls/*.tpl"))
          }

          主頁(yè)面處理如下:

          func?HomeHandler(w?http.ResponseWriter,?r?*http.Request)?{
          ??user,?err?:=?gothic.CompleteUserAuth(w,?r)
          ??if?err?!=?nil?{
          ????http.Redirect(w,?r,?"/login/github",?http.StatusTemporaryRedirect)
          ????return
          ??}
          ??ptTemplate.ExecuteTemplate(w,?"home.tpl",?user)
          }

          如果用戶登錄了,gothic.CompleteUserAuth(w, r)會(huì)返回一個(gè)非空的User對(duì)象,該類型有如下字段:

          type?User?struct?{
          ??RawData???????????map[string]interface{}
          ??Provider??????????string
          ??Email?????????????string
          ??Name??????????????string
          ??FirstName?????????string
          ??LastName??????????string
          ??NickName??????????string
          ??Description???????string
          ??UserID????????????string
          ??AvatarURL?????????string
          ??Location??????????string
          ??AccessToken???????string
          ??AccessTokenSecret?string
          ??RefreshToken??????string
          ??ExpiresAt?????????time.Time
          ??IDToken???????????string
          }

          如果已登錄,顯示主界面信息。如果未登錄,重定向到登錄界面:

          func?LoginHandler(w?http.ResponseWriter,?r?*http.Request)?{
          ??ptTemplate.ExecuteTemplate(w,?"login.tpl",?nil)
          }

          點(diǎn)擊登錄,由AuthHandler處理請(qǐng)求:

          func?AuthHandler(w?http.ResponseWriter,?r?*http.Request)?{
          ??gothic.BeginAuthHandler(w,?r)
          }

          調(diào)用gothic.BeginAuthHandler(w, r)開始跳轉(zhuǎn)到 GitHub 的驗(yàn)證界面。GitHub 驗(yàn)證完成后,瀏覽器會(huì)重定向到/auth/github/callback處理:

          func?CallbackHandler(w?http.ResponseWriter,?r?*http.Request)?{
          ??user,?err?:=?gothic.CompleteUserAuth(w,?r)
          ??if?err?!=?nil?{
          ????fmt.Fprintln(w,?err)
          ????return
          ??}
          ??ptTemplate.ExecuteTemplate(w,?"home.tpl",?user)
          }

          如果登錄成功,在 CallbackHandler 中,我們可以調(diào)用gothic.CompleteUserAuth(w, r)取出User對(duì)象,然后顯示主頁(yè)面。最后是消息路由設(shè)置:

          r?:=?mux.NewRouter()
          r.HandleFunc("/",?HomeHandler)
          r.HandleFunc("/login/github",?LoginHandler)
          r.HandleFunc("/logout/github",?LogoutHandler)
          r.HandleFunc("/auth/github",?AuthHandler)
          r.HandleFunc("/auth/github/callback",?CallbackHandler)

          log.Println("listening?on?localhost:8080")
          log.Fatal(http.ListenAndServe(":8080",?r))

          goth為我們封裝了 GitHub 的驗(yàn)證過程,但是我們需要在 GitHub 上新增一個(gè) OAuth App,生成 Client ID 和 Client Secret。

          首先,登錄 GitHub 賬號(hào),在右側(cè)頭像下拉框選擇 Settings:

          選擇左側(cè) Developer Settings:

          左側(cè)選擇 OAuth App,右側(cè)點(diǎn)擊 New OAuth App:

          輸入信息,重點(diǎn)是Authorization callback URL,這是 GitHub 驗(yàn)證成功之后的回調(diào):

          生成 App 之后,Client ID 會(huì)自動(dòng)生成,但是 Client Secret 需要再點(diǎn)擊右側(cè)的按鈕Generate a new client token生成:

          生成了 Client Secret:

          想要在程序中使用 Github,首先要?jiǎng)?chuàng)建一個(gè) GitHub 的 Provider,調(diào)用github子包的New()方法:

          githubProvider?:=?github.New(clientKey,?clientSecret,?"http://localhost:8080/auth/github/callback")

          第一個(gè)參數(shù)為 Client ID,第二個(gè)參數(shù)為 Client Secret,這兩個(gè)是由上面的 OAuth App 生成的,第三個(gè)參數(shù)為回調(diào)的鏈接,這個(gè)必須與 OAuth App 創(chuàng)建時(shí)設(shè)置的一樣。

          然后應(yīng)用這個(gè) Provider:

          goth.UseProviders(githubProvider)

          準(zhǔn)備工作完成,長(zhǎng)吁一口氣。現(xiàn)在運(yùn)行程序:

          $?SECRET_KEY="secret"?go?run?main.go

          瀏覽器訪問localhost:8080,由于沒有登錄,重定向到localhost:8080/login/github

          點(diǎn)擊Login with GitHub,會(huì)重定向到 GitHub 授權(quán)頁(yè)面:

          點(diǎn)擊授權(quán),成功之后用戶信息會(huì)保存在 session 中。跳轉(zhuǎn)到主頁(yè)面,顯示我的信息:

          更換 store

          goth底層使用上一篇文章中介紹的gorilla/sessions庫(kù)來存儲(chǔ)登錄信息,而默認(rèn)采用的是 cookie 作為存儲(chǔ)。另外選項(xiàng)默認(rèn)采用:

          &Options{
          ??Path:???"/",
          ??Domain:?"",
          ??MaxAge:?86400?*?30,
          ??HttpOnly:?true,
          ??Secure:?false,
          }

          如果需要更改存儲(chǔ)方式或選項(xiàng),我們可以在程序啟動(dòng)前,設(shè)置gothic.Store字段。例如我們要更換為 redistore:

          store,?_?=?redistore.NewRediStore(10,?"tcp",?":6379",?"",?[]byte("redis-key"))

          key?:=?""
          maxAge?:=?86400?*?30??//?30?days
          isProd?:=?false

          store?:=?sessions.NewCookieStore([]byte(key))
          store.MaxAge(maxAge)
          store.Options.Path?=?"/"
          store.Options.HttpOnly?=?true
          store.Options.Secure?=?isProd

          gothic.Store?=?store

          總結(jié)

          大家如果發(fā)現(xiàn)好玩、好用的 Go 語言庫(kù),歡迎到 Go 每日一庫(kù) GitHub 上提交 issue??

          參考

          1. goth GitHub:github.com/markbates/goth
          2. Go 每日一庫(kù) GitHub:https://github.com/darjun/go-daily-lib


          推薦閱讀


          福利

          我為大家整理了一份從入門到進(jìn)階的Go學(xué)習(xí)資料禮包,包含學(xué)習(xí)建議:入門看什么,進(jìn)階看什么。關(guān)注公眾號(hào) 「polarisxu」,回復(fù) ebook 獲取;還可以回復(fù)「進(jìn)群」,和數(shù)萬 Gopher 交流學(xué)習(xí)。

          瀏覽 31
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  香蕉视频二区 | 亚洲网站在线免费观看 | 成人视频网站久久久精品网站久久久 | 成人AV高清无码在线观 | 青娱乐久久国产 |