go?goth封裝第三方認證庫示例詳解
簡介
當(dāng)前很多網(wǎng)站直接采用第三方認證登錄,例如支付寶/微信/ Github 等。goth封裝了接入第三方認證的方法,并且內(nèi)置實現(xiàn)了很多第三方認證的實現(xiàn):
圖中截取的只是goth
支持的一部分,完整列表可在其GitHub 首頁查看。
快速使用
本文代碼使用 Go Modules。
創(chuàng)建目錄并初始化:
$ mkdir goth && cd goth $ go mod init github.com/darjun/go-daily-lib/goth
安裝goth
庫:
$ go get -u github.com/markbates/goth
我們設(shè)計了兩個頁面,一個登錄頁面:
// login.tpl <a href="/auth/github?provider=github" rel="external nofollow" >Login With GitHub</a>
點擊登錄鏈接會請求/auth/github?provider=github
。
一個主界面:
// 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
標準模板庫來加載和管理頁面模板:
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)
會返回一個非空的User
對象,該類型有如下字段:
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) }
點擊登錄,由AuthHandler
處理請求:
func AuthHandler(w http.ResponseWriter, r *http.Request) { gothic.BeginAuthHandler(w, r) }
調(diào)用gothic.BeginAuthHandler(w, r)
開始跳轉(zhuǎn)到 GitHub 的驗證界面。GitHub 驗證完成后,瀏覽器會重定向到/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
對象,然后顯示主頁面。最后是消息路由設(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 的驗證過程,但是我們需要在 GitHub 上新增一個 OAuth App,生成 Client ID 和 Client Secret。
首先,登錄 GitHub 賬號,在右側(cè)頭像下拉框選擇 Settings:
選擇左側(cè) Developer Settings:
左側(cè)選擇 OAuth App,右側(cè)點擊 New OAuth App:
輸入信息,重點是Authorization callback URL
,這是 GitHub 驗證成功之后的回調(diào):
生成 App 之后,Client ID 會自動生成,但是 Client Secret 需要再點擊右側(cè)的按鈕Generate a new client token
生成:
生成了 Client Secret:
想要在程序中使用 Github,首先要創(chuàng)建一個 GitHub 的 Provider,調(diào)用github
子包的New()
方法:
githubProvider := github.New(clientKey, clientSecret, "http://localhost:8080/auth/github/callback")
第一個參數(shù)為 Client ID,第二個參數(shù)為 Client Secret,這兩個是由上面的 OAuth App 生成的,第三個參數(shù)為回調(diào)的鏈接,這個必須與 OAuth App 創(chuàng)建時設(shè)置的一樣。
然后應(yīng)用這個 Provider:
goth.UseProviders(githubProvider)
準備工作完成,長吁一口氣?,F(xiàn)在運行程序:
$ SECRET_KEY="secret" go run main.go
瀏覽器訪問localhost:8080
,由于沒有登錄,重定向到localhost:8080/login/github
:
點擊Login with GitHub
,會重定向到 GitHub 授權(quán)頁面:
點擊授權(quán),成功之后用戶信息會保存在 session
中。跳轉(zhuǎn)到主頁面,顯示我的信息:
更換 store
goth
底層使用上一篇文章中介紹的gorilla/sessions庫來存儲登錄信息,而默認采用的是 cookie 作為存儲。另外選項默認采用:
如果需要更改存儲方式或選項,我們可以在程序啟動前,設(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 語言庫,歡迎到 Go 每日一庫 GitHub 上提交 issue??
參考
goth GitHub:https://github.com/markbates/goth
Go 每日一庫 GitHub:https://github.com/darjun/go-daily-lib
以上就是go goth封裝第三方認證庫示例詳解的詳細內(nèi)容,更多關(guān)于go goth第三方認證庫的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Go實現(xiàn)自動解壓縮包以及讀取docx/doc文件內(nèi)容詳解
在開發(fā)過程中,我們常常需要處理壓縮包和文檔文件。本文將介紹如何使用Go語言自動解壓縮包和讀取docx/doc文件,需要的可以參考一下2023-03-03GoLang string與strings.Builder使用對比詳解
這篇文章主要介紹了GoLang string與strings.Builder使用對比,Builder 用于使用 Write 方法有效地構(gòu)建字符串。它最大限度地減少了內(nèi)存復(fù)制。零值可以使用了。不要復(fù)制非零生成器2023-03-03golang中實現(xiàn)給gif、png、jpeg圖片添加文字水印
這篇文章主要介紹了golang中實現(xiàn)給gif、png、jpeg圖片添加文字水印,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04