go?goth封裝第三方認(rèn)證庫(kù)示例詳解
簡(jiǎn)介
當(dāng)前很多網(wǎng)站直接采用第三方認(rèn)證登錄,例如支付寶/微信/ Github 等。goth封裝了接入第三方認(rèn)證的方法,并且內(nèi)置實(shí)現(xiàn)了很多第三方認(rèn)證的實(shí)現(xiàn):
圖中截取的只是goth
支持的一部分,完整列表可在其GitHub 首頁查看。
快速使用
本文代碼使用 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è)頁面,一個(gè)登錄頁面:
// login.tpl <a href="/auth/github?provider=github" rel="external nofollow" >Login With GitHub</a>
點(diǎn)擊登錄鏈接會(huì)請(qǐng)求/auth/github?provider=github
。
一個(gè)主界面:
// home.tpl <p><a href="/logout/github" rel="external nofollow" >logout</a></p> <p>Name: {{.Name}} [{{.LastName}}, {{.FirstName}}]</p> <p>Email: {{.Email}}</p> <p>NickName: {{.NickName}}</p> <p>Location: {{.Location}}</p> <p>AvatarURL: {{.AvatarURL}} <img src="{{.AvatarURL}}"></p> <p>Description: {{.Description}}</p> <p>UserID: {{.UserID}}</p> <p>AccessToken: {{.AccessToken}}</p> <p>ExpiresAt: {{.ExpiresAt}}</p> <p>RefreshToken: {{.RefreshToken}}</p>
顯示用戶的基本信息。
同樣地,我們使用html/template
標(biāo)準(zhǔn)模板庫(kù)來加載和管理頁面模板:
var ( ptTemplate *template.Template ) func init() { ptTemplate = template.Must(template.New("").ParseGlob("tpls/*.tpl")) }
主頁面處理如下:
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ì)象,然后顯示主頁面。最后是消息路由設(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)吁一口氣?,F(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)頁面:
點(diǎn)擊授權(quán),成功之后用戶信息會(huì)保存在 session
中。跳轉(zhuǎn)到主頁面,顯示我的信息:
更換 store
goth
底層使用上一篇文章中介紹的gorilla/sessions庫(kù)來存儲(chǔ)登錄信息,而默認(rèn)采用的是 cookie 作為存儲(chǔ)。另外選項(xiàng)默認(rèn)采用:
如果需要更改存儲(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??
參考
goth GitHub:https://github.com/markbates/goth
Go 每日一庫(kù) GitHub:https://github.com/darjun/go-daily-lib
以上就是go goth封裝第三方認(rèn)證庫(kù)示例詳解的詳細(xì)內(nèi)容,更多關(guān)于go goth第三方認(rèn)證庫(kù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Go實(shí)現(xiàn)自動(dòng)解壓縮包以及讀取docx/doc文件內(nèi)容詳解
在開發(fā)過程中,我們常常需要處理壓縮包和文檔文件。本文將介紹如何使用Go語言自動(dòng)解壓縮包和讀取docx/doc文件,需要的可以參考一下2023-03-03GoLang string與strings.Builder使用對(duì)比詳解
這篇文章主要介紹了GoLang string與strings.Builder使用對(duì)比,Builder 用于使用 Write 方法有效地構(gòu)建字符串。它最大限度地減少了內(nèi)存復(fù)制。零值可以使用了。不要復(fù)制非零生成器2023-03-03golang中實(shí)現(xiàn)給gif、png、jpeg圖片添加文字水印
這篇文章主要介紹了golang中實(shí)現(xiàn)給gif、png、jpeg圖片添加文字水印,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-04-04