英文:
How to send authentication token using curl in golang?
问题
你好!要使用curl传递身份验证令牌,你可以使用以下命令:
curl -X GET -H "Authorization: Bearer <token>" http://localhost:8000/your-endpoint
将<token>
替换为你的身份验证令牌。这将在请求头中添加一个名为"Authorization"的字段,并将其值设置为"Bearer c.Request.Header.Get("Authorization")
来获取该令牌并进行验证。
希望对你有所帮助!如果你有任何其他问题,请随时问我。
英文:
I'm trying to use authentication model to my golang API and I'm using gin framework. I want to send authentication token using curl, then validate it and do all the crud operation after the authentication happens.
My code is like this:
func TokenAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.Request.FormValue("token")
if token == "" {
respondWithError(401, "API token required", c)
return
}
if token != os.Getenv("API_TOKEN") {
respondWithError(401, "Invalid API token", c)
return
}
c.Next()
}
}
func respondWithError(code int, message string,c *gin.Context) {
resp := map[string]string{"error": message}
c.JSON(code, resp)
c.Abort()
}
Main function:
func main() {
router := gin.Default()
router.Use(TokenAuthMiddleware())
router.Run(":8000")
}
How can I pass the authentication token using curl?
答案1
得分: 2
c.Request.FormValue("token")
期望通过 application/x-www-form-urlencoded
的 POST 请求发送令牌。使用 cURL 可以这样实现:
$ curl -i --data "token=<token>" https://example.org/endpoint
这种方法的缺点是,对于每个请求,你的 POST
请求必须包含一个令牌值 - 但是如果你想使用 GET
或 DELETE
请求呢?
就像 @elithrar 所说的,使用 Authorization
头部发送身份验证令牌更有意义。通过 cURL 在头部发送身份验证令牌非常简单,使用 -H
标志,例如:
$ curl -i POST -H "Authorization: Bearer <token>" --data "key1=value1&key2=value2" https://example.org
签署身份验证令牌的正确方法是使用 JWT。我推荐使用 dgrijalva/jwt-go
来使用 JWT。
如果你只需要一个用户访问你的 API,那么实际上不需要 JWT。只需确保你的身份验证令牌是(伪)随机生成的,例如使用 openssl
库:
$ openssl rand -out $GOPATH/bin/token.key -base64 128
英文:
c.Request.FormValue("token")
expects that the token is send through a application/x-www-form-urlencoded
POST request. To accomplish this with cURL you can do something as following:
$ curl -i --data "token=<token>" https://example.org/endpoint
The downside of this method is that for every request, your POST
request must contain a token value - but what if you want to use a GET
or DELETE
request?
Like @elithrar said, it would make more sense to send the authentication token with an Authorization
header. Sending the authentication token in the header via cURL is quite easy, use the -H
flag, e.g.
$ curl -i POST -H "Authorization: Bearer <token>" --data "key1=value1&key2=value2" https://example.org
A proper way of signing your authentication token is by using JWT. I would recommend dgrijalva/jwt-go
for using JWT.
If you only require one user to access your API, there's no real need for JWT though. Just make sure your authentication token are (pseudo-)randomly generated, e.g. with the openssl
library:
$ openssl rand -out $GOPATH/bin/token.key -base64 128
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论