英文:
Go and JWT - Simple authentication
问题
我目前正在制作一个API(使用Go语言),并且正在处理会话部分。
在研究了关于会话使用的内容后,我发现JWT非常有趣。
然而,通过一些教程后,我并不确定如何使用它。
所以这是我的想法:
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/login", login)
router.HandleFunc("/logout", logout)
router.HandleFunc("/register", register)
http.ListenAndServe(":8080", router)
}
在处理这些请求之后,我创建了不同的函数。
func login(w http.ResponseWriter, r *http.Request) {
/*
在这里,我只需要在我的数据库中搜索(使用SQL,我知道如何做)。如果用户已注册,我会创建一个令牌并将其提供给他,但是我该如何做呢?
*/
}
func logout(w http.ResponseWriter, r *http.Request) {
/*
我获取一个令牌并停止/删除它?
*/
}
func register(w http.ResponseWriter, r *http.Request) {
/*
我搜索用户是否已注册,然后如果没有注册,我在数据库中创建一个用户(我知道如何做)。我连接他,但是如何生成一个新的令牌呢?
*/
}
网络上的许多教程似乎非常复杂,但我只想要简单的东西。我只想要一个处理包(上面的代码),它与服务包一起工作,以实现类似于引擎令牌认证的功能。
我还不确定的第二个问题是令牌的保存。
如果用户连接自己,那么什么是最好的方式?每次用户运行他们的应用程序时,应用程序都会连接并从保存的信息(用户/密码)获取一个新的令牌,还是应用程序永久保存令牌?服务器如何处理,令牌是否由JWT自动管理和保存,还是我需要将其放入我的SQL数据库中?
谢谢你的帮助!
编辑1
谢谢!所以在阅读了你的回答后,我将我的代码(token.go)封装如下:
package services
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"time"
"../models"
)
var tokenEncodeString string = "something"
func createToken(user models.User) (string, error) {
// 创建令牌
token := jwt.New(jwt.SigningMethodHS256)
// 设置一些声明
token.Claims["username"] = user.Username;
token.Claims["password"] = user.Password;
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
// 签名并将完整的编码令牌作为字符串返回
return (token.SignedString(tokenEncodeString))
}
func parseToken(unparsedToken string) (bool, string) {
token, err := jwt.Parse(unparsedToken, func(token *jwt.Token) (interface{}, error) {
// 不要忘记验证算法是否符合预期:
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return myLookupKey(token.Header["kid"]), nil
})
if err == nil && token.Valid {
return true, unparsedToken
} else {
return false, ""
}
}
然而,我遇到了以下错误:"token.go: undefined: myLookupKey"。
我在互联网上搜索并找到了一个封装的函数,它具有以下原型:
func ExampleParse(myToken string, myLookupKey func(interface{}) (interface{}, error)) {
/* 与我的func parseToken()中的代码相同 */
}
那么我的函数和这个函数有什么区别?我该如何使用这个函数?
谢谢!
英文:
I'm currently making an API (with go) and I'm working on the session part.
After research about what to use for session, I found JWT really interesting.
However I'm not really sure to understand how to use it after some tutorials.
So this is my idea:
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/login", login)
router.HandleFunc("/logout", logout)
router.HandleFunc("/register", register)
http.ListenAndServe(":8080", router)
}
After those requests handled, I create the differents functions.
func login(w http.ResponseWriter, r *http.Request) {
/*
Here I just have to search in my database (SQL, I know how to do it). If the user is registered, I create a token and give it to him, but how can I do it?
*/
}
func logout(w http.ResponseWriter, r *http.Request) {
/*
I get a token and stop/delete it?
*/
}
func register(w http.ResponseWriter, r *http.Request) {
/*
I search if the user isn't register and then, if it isn't, I create a user in the database (I know how to do it). I connect him but again, how to make a new token?
*/
}
Lot of tutorials on the web seems really hard but I just want something simple. I just want an handle package (code above) which work with a service package to have something like an engine token authentication.
A second point I'm not sure to understand is the saving of the token.
If a user connects himself, then what would be best? Each time the user runs their app, the app connects itself and get a new token from saved information (user/password) or the app just save the token forever? And what about the server, is the token managed and saved automatically with JWT or do I have to put it in my sql database?
Thank for your help !
EDIT 1
Thank you ! So after I read your answer, I encapsulated my code (token.go) like it
package services
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"time"
"../models"
)
var tokenEncodeString string = "something"
func createToken(user models.User) (string, error) {
// create the token
token := jwt.New(jwt.SigningMethodHS256)
// set some claims
token.Claims["username"] = user.Username;
token.Claims["password"] = user.Password;
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
//Sign and get the complete encoded token as string
return (token.SignedString(tokenEncodeString))
}
func parseToken(unparsedToken string) (bool, string) {
token, err := jwt.Parse(unparsedToken, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return myLookupKey(token.Header["kid"]), nil
})
if err == nil && token.Valid {
return true, unparsedToken
} else {
return false, ""
}
}
However, I got the following error: "token.go: undefined: myLookupKey"
I looked on internet and I found an encapsulated function which have this prototype:
func ExampleParse(myToken string, myLookupKey func(interface{}) (interface{}, error)) {
/* same code in my func parseToken() */
}
So what are the difference between my function and this one? How can I use this one?
Thanks !
答案1
得分: 31
注意:
这个包 github.com/dgrijalva/jwt-go 已经被弃用,请使用 github.com/golang-jwt/jwt 替代。
首先,你需要在 Golang 中导入一个 JWT 库(go get github.com/dgrijalva/jwt-go)。你可以在下面的链接中找到该库的文档。
https://github.com/dgrijalva/jwt-go
首先,你需要创建一个令牌
// 创建令牌
token := jwt.New(jwt.SigningMethodHS256)
// 设置一些声明
token.Claims["foo"] = "bar"
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
// 签名并将完整的编码令牌作为字符串返回
tokenString, err := token.SignedString(mySigningKey)
其次,解析该令牌
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
// 不要忘记验证 alg 是否符合预期:
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return myLookupKey(token.Header["kid"]), nil
})
if err == nil && token.Valid {
deliverGoodness("!")
} else {
deliverUtterRejection(":(")
}
此外,还有一些在 Golang 中使用 JWT 的示例,例如 https://github.com/slok/go-jwt-example
编辑-1
package main
import (
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
)
const (
mySigningKey = "WOW,MuchShibe,ToDogge"
)
func main() {
createdToken, err := ExampleNew([]byte(mySigningKey))
if err != nil {
fmt.Println("创建令牌失败")
}
ExampleParse(createdToken, mySigningKey)
}
func ExampleNew(mySigningKey []byte) (string, error) {
// 创建令牌
token := jwt.New(jwt.SigningMethodHS256)
// 设置一些声明
token.Claims["foo"] = "bar"
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
// 签名并将完整的编码令牌作为字符串返回
tokenString, err := token.SignedString(mySigningKey)
return tokenString, err
}
func ExampleParse(myToken string, myKey string) {
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
return []byte(myKey), nil
})
if err == nil && token.Valid {
fmt.Println("你的令牌有效。我喜欢你的风格。")
} else {
fmt.Println("这个令牌太糟糕了!我不能接受这个。")
}
}
英文:
Note:
This package github.com/dgrijalva/jwt-go is deprecated use this instead github.com/golang-jwt/jwt
To start, you need to import a JWT library in Golang (go get github.com/dgrijalva/jwt-go). You can find that library documentation in below link.
https://github.com/dgrijalva/jwt-go
Firstly, you need to create a token
// Create the token
token := jwt.New(jwt.SigningMethodHS256)
// Set some claims
token.Claims["foo"] = "bar"
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
// Sign and get the complete encoded token as a string
tokenString, err := token.SignedString(mySigningKey)
Secondly, parse that token
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return myLookupKey(token.Header["kid"]), nil
})
if err == nil && token.Valid {
deliverGoodness("!")
} else {
deliverUtterRejection(":(")
}
Also, there are some examples for use JWT in GOlang like this https://github.com/slok/go-jwt-example
EDIT-1
package main
import (
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
)
const (
mySigningKey = "WOW,MuchShibe,ToDogge"
)
func main() {
createdToken, err := ExampleNew([]byte(mySigningKey))
if err != nil {
fmt.Println("Creating token failed")
}
ExampleParse(createdToken, mySigningKey)
}
func ExampleNew(mySigningKey []byte) (string, error) {
// Create the token
token := jwt.New(jwt.SigningMethodHS256)
// Set some claims
token.Claims["foo"] = "bar"
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
// Sign and get the complete encoded token as a string
tokenString, err := token.SignedString(mySigningKey)
return tokenString, err
}
func ExampleParse(myToken string, myKey string) {
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
return []byte(myKey), nil
})
if err == nil && token.Valid {
fmt.Println("Your token is valid. I like your style.")
} else {
fmt.Println("This token is terrible! I cannot accept this.")
}
}
答案2
得分: 11
只是为了更新@massoud-afrashteh的答案。
在jwt-go的第3个版本中,设置声明应该是这样的:
// 设置一些声明
claims := make(jwt.MapClaims)
claims["foo"] = "bar"
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
token.Claims = claims
英文:
Just to make update of @massoud-afrashteh answer.
In version 3 of jwt-go setting clams should be
// Set some claims
claims := make(jwt.MapClaims)
claims["foo"] = "bar"
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
token.Claims = claims
答案3
得分: 4
不要忘记运行命令 go get github.com/dgrijalva/jwt-go
。
另一种更简单的创建方式:
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"foo": "bar",
"nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
})
tokenString, err := token.SignedString([]byte("your key"))
fmt.Println(tokenString, err)
英文:
Don't forget to run the command go get github.com/dgrijalva/jwt-go
.
Another way to create more simple:
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"foo": "bar",
"nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
})
tokenString, err := token.SignedString([]byte("your key"))
fmt.Println(tokenString, err)
答案4
得分: 1
func GenerateToken(mySigningKey []byte, username string) (string, error) {
// 创建令牌
token := jwt.New(jwt.SigningMethodRS512)
claims := make(jwt.MapClaims)
claims[collections.PARAM_USER_NAME] = username
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
token.Claims = claims
return token.SignedString(mySigningKey)
}
英文:
func GenerateToken(mySigningKey []byte, username string) (string, error) {
// Create the token
token := jwt.New(jwt.SigningMethodRS512)
claims := make(jwt.MapClaims)
claims[collections.PARAM_USER_NAME] = username
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
token.Claims = claims
return token.SignedString(mySigningKey)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论