如何在go-swagger中使用代码401或404来响应无效的令牌而不是500?

huangapple go评论74阅读模式
英文:

How to respond with code 401 or 404 instead of 500 in go-swagger for invalid bearer token

问题

我使用go-swagger创建了一个REST API服务器,并在几个端点上添加了Bearer令牌安全性。根据文档,令牌验证方法的签名应该是func(string) (interface{}, error)

如果传递的Bearer令牌无效,令牌验证方法将返回一个错误。这将导致向请求者返回带有JSON响应体的500响应:

{
    "code": 500,
    "message": "Token is expired"
}

然而,作为标准,我如何使此响应具有401代码。

注意:关于Java的类似讨论可以在https://stackoverflow.com/a/60738107/16087692找到,有没有办法在Go中实现这个?

英文:

I have created a REST API server using go-swagger and added bearer token security to a few endpoints. As per docs, the token verification method should have a signature like func(string) (interface{}, error).

The token verification method returns an error if the passed bearer token is not valid. This results in 500 responses to the requestor with JSON response body:

{
	"code": 500,
	"message": "Token is expired"
}

However, as standers how can I make this response with code 401.

Note: A similar discussion like this for Java can be found at https://stackoverflow.com/a/60738107/16087692 , Is there any way to achieve this Go?

答案1

得分: 2

我对go-swagger没有经验,但刚好看到了这个问题。
答案在示例中:
https://github.com/go-swagger/go-swagger/tree/master/examples/authentication

示例显示该函数返回一个错误:

errors.New(401, "incorrect api key auth")

这是来自包"github.com/go-openapi/errors"的错误,你可以传入一个HTTP状态码。

英文:

I've no experience with go-swagger but just stumbled upon this question.
The answer is in the examples:
https://github.com/go-swagger/go-swagger/tree/master/examples/authentication

The example shows that the function returns an:

errors.New(401, "incorrect api key auth")

This is an error from the package: "github.com/go-openapi/errors" where you can pass in a http status code.

huangapple
  • 本文由 发表于 2021年11月4日 19:54:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/69838837.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定