go goth封装第三方认证库示例详解


Posted in Golang onAugust 14, 2022

简介

当前很多网站直接采用第三方认证登录,例如支付宝/微信/ Github 等。goth封装了接入第三方认证的方法,并且内置实现了很多第三方认证的实现:

go goth封装第三方认证库示例详解

图中截取的只是goth支持的一部分,完整列表可在其GitHub 首页查看。

快速使用

本文代码使用 Go Modules。

创建目录并初始化:

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

安装goth库:

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

我们设计了两个页面,一个登录页面:

// 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)
}

调用gothic.BeginAuthHandler(w, r)开始跳转到 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 中,我们可以调用gothic.CompleteUserAuth(w, r)取出User对象,然后显示主页面。最后是消息路由设置:

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 账号,在右侧头像下拉框选择 Settings:

go goth封装第三方认证库示例详解

选择左侧 Developer Settings:

go goth封装第三方认证库示例详解

左侧选择 OAuth App,右侧点击 New OAuth App:

go goth封装第三方认证库示例详解

输入信息,重点是Authorization callback URL,这是 GitHub 验证成功之后的回调:

go goth封装第三方认证库示例详解

生成 App 之后,Client ID 会自动生成,但是 Client Secret 需要再点击右侧的按钮Generate a new client token生成:

go goth封装第三方认证库示例详解

生成了 Client Secret:

go goth封装第三方认证库示例详解

想要在程序中使用 Github,首先要创建一个 GitHub 的 Provider,调用github子包的New()方法:

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

第一个参数为 Client ID,第二个参数为 Client Secret,这两个是由上面的 OAuth App 生成的,第三个参数为回调的链接,这个必须与 OAuth App 创建时设置的一样。

然后应用这个 Provider:

goth.UseProviders(githubProvider)

准备工作完成,长吁一口气。现在运行程序:

$ SECRET_KEY="secret" go run main.go

浏览器访问localhost:8080,由于没有登录,重定向到localhost:8080/login/github

go goth封装第三方认证库示例详解

点击Login with GitHub,会重定向到 GitHub 授权页面:

go goth封装第三方认证库示例详解

点击授权,成功之后用户信息会保存在 session
中。跳转到主页面,显示我的信息:

go goth封装第三方认证库示例详解

更换 store

goth底层使用上一篇文章中介绍的gorilla/sessions库来存储登录信息,而默认采用的是 cookie 作为存储。另外选项默认采用:

如果需要更改存储方式或选项,我们可以在程序启动前,设置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

总结

大家如果发现好玩、好用的 Go 语言库,欢迎到 Go 每日一库 GitHub 上提交 issue?

参考

goth GitHub:https://github.com/markbates/goth

Go 每日一库 GitHub:https://github.com/darjun/go-daily-lib

以上就是go goth封装第三方认证库示例详解的详细内容,更多关于go goth第三方认证库的资料请关注三水点靠木其它相关文章!

Golang 相关文章推荐
golang中的空slice案例
Apr 27 Golang
解决Golang中ResponseWriter的一个坑
Apr 27 Golang
go 原生http web 服务跨域restful api的写法介绍
Apr 27 Golang
Go语言中break label与goto label的区别
Apr 28 Golang
解决golang post文件时Content-Type出现的问题
May 02 Golang
Goland使用Go Modules创建/管理项目的操作
May 06 Golang
浅谈Golang 切片(slice)扩容机制的原理
Jun 09 Golang
试了下Golang实现try catch的方法
Jul 01 Golang
基于Go语言构建RESTful API服务
Jul 25 Golang
Go语言特点及基本数据类型使用详解
Mar 21 Golang
Go gorilla securecookie库的安装使用详解
Aug 14 Golang
基于Python实现西西成语接龙小助手
Aug 05 #Golang
Python测试框架pytest核心库pluggy详解
Aug 05 #Golang
Go结合Gin导出Mysql数据到Excel表格
Aug 05 #Golang
GO中sync包自由控制并发示例详解
Aug 05 #Golang
Go语言编译原理之源码调试
Aug 05 #Golang
Go语言编译原理之变量捕获
Aug 05 #Golang
在ubuntu下安装go开发环境的全过程
Aug 05 #Golang
You might like
php基础知识:控制结构
2006/12/13 PHP
解析php安全性问题中的:Null 字符问题
2013/06/21 PHP
php curl选项列表(超详细)
2013/07/01 PHP
php通过递归方式复制目录和子目录的方法
2015/03/13 PHP
php判断是否连接上网络的方法实例详解
2016/12/14 PHP
PHP巧妙利用位运算实现网站权限管理的方法
2017/03/12 PHP
关于JavaScript对象的动态选择及遍历对象
2014/03/10 Javascript
如何实现JavaScript动态加载CSS和JS文件
2020/12/28 Javascript
详解AngularJS中自定义过滤器
2015/12/28 Javascript
AngularJS基础 ng-cloak 指令简单示例
2016/08/01 Javascript
基于JavaScript实现在新的tab页打开url
2016/08/04 Javascript
js 能实现监听F5页面刷新子iframe 而父页面不刷新的方法
2016/11/09 Javascript
详解基于webpack2.x的vue2.x的多页面站点
2017/08/21 Javascript
Nodejs实现文件上传的示例代码
2017/09/26 NodeJs
vue2导航根据路由传值,而改变导航内容的实例
2017/11/10 Javascript
jQuery niceScroll滚动条错位问题的解决方法
2018/02/03 jQuery
vue监听键盘事件的快捷方法【推荐】
2018/07/11 Javascript
如何给element添加一个抽屉组件的方法步骤
2019/07/14 Javascript
Python3遍历目录树实现方法
2015/05/22 Python
python利用标准库如何获取本地IP示例详解
2017/11/01 Python
Python开发虚拟环境使用virtualenvwrapper的搭建步骤教程图解
2018/09/19 Python
启动Atom并运行python文件的步骤
2018/11/09 Python
Flask之请求钩子的实现
2018/12/23 Python
PyQt5图形界面播放音乐的实例
2019/06/17 Python
python求平均数、方差、中位数的例子
2019/08/22 Python
Python3实现将一维数组按标准长度分隔为二维数组
2019/11/29 Python
Python如何解除一个装饰器
2020/08/07 Python
VICHY薇姿英国官网:全球专业敏感肌护肤领先品牌
2017/07/04 全球购物
美国最大的船只买卖在线市场:Boat Trader
2018/08/04 全球购物
初中教师业务学习材料
2014/05/12 职场文书
奶茶店创业计划书
2014/08/14 职场文书
个人工作表现评价材料
2014/09/21 职场文书
2014年应急工作总结
2014/12/11 职场文书
婚礼双方父亲致辞
2015/07/27 职场文书
2016年主题党日活动总结
2016/04/05 职场文书
Navicat Premium自定义 sql 标签的创建方式
2022/09/23 数据库