编写用例以验证OAuth令牌的方法
编写单元或集成测试用例来验证启用 OAuth 的后端服务需要考虑验证令牌的有效性。对于启用 OAuth 的 GoLang 后端服务,可以使用中间件函数来验证 Authorization 标头中的 OAuth 令牌。此函数应检查令牌格式、验证令牌并检查令牌过期时间。使用测试框架(如 httptest)创建模拟 HTTP 请求并设置 Authorization 标头,可以测试此中间件函数在各种场景下的行为,包括没有令牌、格式错误的令牌、过期的令牌和有效的令牌。
我们有一个接受 http 请求的 GoLang 后端服务(启用 OAuth),其 Authorization 标头的值为 "Bearer" + OAuthTokenString。
如何为后端服务编写单元或集成测试用例以验证后端服务是否启用了 OAuth(验证令牌)?我不确定,我们无法创建启用 OAuth 的模拟服务(httptest.NewServer)....
正确答案
这是一个非常有趣的问题。我可以看到您的团队关心的是通过测试代码来最大限度地减少可能的错误。这是许多开发人员经常忘记的一个方面。
在没有看过您的代码的情况下,很难为您的案例提出 100% 正确的答案。
我假设我的示例将作为编写您自己的测试的指南,或者在最好的情况下优化我建议的示例
我使用 gin gonic 作为我的项目的 http web 框架,并编写了一个方法 authenticate,该方法被称为每个受保护端点的中间件。然后为了测试我只通过 gin.default () 方法创建了一个http服务器
// authenticate auth an endpoint
func authenticate() gin.handlerfunc {
return func(c *gin.context) {
var someerr errors.bukyerror
someerr.setunauthorized()
// fetch token from the headers
requiredtoken := c.getheader(constants.authorizationheader)
if len(requiredtoken) == 0 {
c.abortwithstatusjson(someerr.httperrorcode, someerr.json())
return
}
splittedtoken := strings.splitn(requiredtoken, " ", 2)
if len(splittedtoken) != 2 || strings.tolower(splittedtoken[0]) != "bearer" {
primerr := fmt.errorf("wrong bearer token format on authorization header")
someerr.primitiveerr = &primerr
c.abortwithstatusjson(someerr.httperrorcode, someerr.json())
return
}
// get email from encoded token
jwttoken, claims, err := helpers.decodejwt(splittedtoken[1], false)
if err != nil {
someerr.primitiveerr = &err
c.abortwithstatusjson(someerr.httperrorcode, someerr.json())
return
}
if _, err := helpers.verifyobjectids(claims.subject); !err.isnilerror() {
c.abortwithstatusjson(someerr.httperrorcode, someerr.json())
return
}
// set the user variable so that we can easily retrieve from other middlewares
// c.set("user", result)
c.set(constants.reqbukyjwtkey, jwttoken)
c.set(constants.reqbukyclaimskey, claims)
// call the next middlware
c.next()
}
}
然后我就像下面这样进行测试
func TestAuthenticate(t *testing.T) {
userID := primitive.NewObjectID().Hex()
email := "[email protected]"
firstName := "My Name"
lastName := "My Lastname"
scopes := []string{"im_scope"}
statusOK := "statusOK"
someProtectedPath := constants.UsersPath + "/" + userID
engine := gin.Default()
engine.GET(someProtectedPath, Authenticate(), func(c *gin.Context) {
c.String(http.StatusOK, statusOK)
})
t.Run("NoTokenHeader", func(t *testing.T) {
t.Run("UnsetHeader", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", someProtectedPath, nil)
engine.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
})
t.Run("EmptyHeader", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", someProtectedPath, nil)
req.Header.Set(constants.AuthorizationHeader, "")
engine.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
})
})
t.Run("TokenWithBadFormat", func(t *testing.T) {
t.Run("1", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", someProtectedPath, nil)
badFormatedToken := "hola.hola"
req.Header.Set(constants.AuthorizationHeader, fmt.Sprintf("Bearer %s", badFormatedToken))
engine.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
})
t.Run("2", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", someProtectedPath, nil)
badFormatedToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ."
req.Header.Set(constants.AuthorizationHeader, fmt.Sprintf("Bearer %s", badFormatedToken))
engine.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
})
t.Run("3", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", someProtectedPath, nil)
badFormatedToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.hola.hola.hola"
req.Header.Set(constants.AuthorizationHeader, fmt.Sprintf("Bearere %s", badFormatedToken))
engine.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
})
})
t.Run("ExpiredToken", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", someProtectedPath, nil)
expirationTime := time.Second
expiredToken, _, err := helpers.GenerateAccessJWT(userID, email, firstName, lastName, scopes, expirationTime)
time.Sleep(expirationTime * 2)
req.Header.Set(constants.AuthorizationHeader, fmt.Sprintf("Bearer %s", expiredToken))
engine.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
assert.Nil(t, err)
})
t.Run("ValidToken", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", someProtectedPath, nil)
validToken, _, err := helpers.GenerateAccessJWT(userID, email, firstName, lastName, scopes)
req.Header.Set(constants.AuthorizationHeader, fmt.Sprintf("Bearer %s", validToken))
engine.ServeHTTP(w, req)
assert.Nil(t, err)
assert.Equal(t, http.StatusOK, w.Code)
})
}以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
如何解决Windows 7配置更新失败问题
- 上一篇
- 如何解决Windows 7配置更新失败问题
- 下一篇
- 阿里云将于 3 月 29 日停止商标代理服务,未来将着重于平台开放第三方服务
-
- Golang · Go问答 | 1天前 | 标准库 · JSON · Go问答 · 版本迁移 · JSON Go unmarshal 工具链 jsonv2 encoding/json/v2 GOEXPERIMENT
- Go encoding/json/v2.Unmarshal 为什么 json/v2 仍然要用实验开关隔离部署
- 476浏览 收藏
-
- Golang · Go问答 | 1天前 | 标准库 · 故障排查 · Go问答 · 分隔符 Go filepath.Match 路径匹配 path.Match
- Go path.Match 为什么 Match 的斜杠和 filepath.Match 不能混用
- 178浏览 收藏
-
- Golang · Go问答 | 1天前 | 标准库 · 错误处理 · Go问答 · Go 跨平台 io/fs.ValidPath filepath.Localize 路径转换
- Go filepath.Localize 为什么 Localize 要求输入满足 io/fs.ValidPath
- 290浏览 收藏
-
- Golang · Go问答 | 1天前 |
- Go os.Root.Close 为什么关闭 Root 后派生文件句柄仍需单独管理
- 193浏览 收藏
-
- Golang · Go问答 | 1天前 |
- Go os.Root.Remove 为什么 Remove 仍要区分文件和目录错误
- 327浏览 收藏
-
- Golang · Go问答 | 1天前 | 标准库 · Go问答 · 文件系统 · Go 目录创建 文件系统边界 os.Root.Mkdir Root.MkdirAll
- Go os.Root.Mkdir 为什么 MkdirAll 不能无条件替代 Root.Mkdir
- 419浏览 收藏
-
- Golang · Go问答 | 1天前 |
- Go os.Root.Stat 为什么 Stat 的路径解析和工作目录不同
- 254浏览 收藏
-
- Golang · Go问答 | 1天前 | 标准库 · HTTP · Go问答 · Go httptrace ClientTrace WroteHeaders WroteRequest HTTP观测
- Go httptrace.WroteHeaders 为什么 WroteHeaders 不能代表服务器已经处理请求
- 237浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 1162次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 1147次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 1324次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 1267次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 1125次使用
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go maps.Clone 为什么 Clone 只复制映射结构而不是深拷贝值
- 2026-11-20 501浏览
-
- Go index/suffixarray.Index.Bytes 怎样取得索引引用的原始数据
- 2026-11-18 501浏览
-
- Go gosym.Sym.BaseName 怎样去掉符号的包名与接收者
- 2026-11-17 501浏览

