Click here for an implementation example.
https://github.com/ken109/gin-jwt-example
- Issuance of private key
openssl genrsa -out private.key 2048
- Add Import
import (
"github.com/ken109/gin-jwt"
)
- Set private key, Issuer, etc.
func main() {
pemBytes, err := ioutil.ReadFile("private.key")
if err != nil {
panic(err)
}
// here
err := jwt.SetUp(pemBytes, jwt.Option{
Issuer: "[email protected]",
Subject: "[email protected]",
KeyId: "test",
Expiration: time.Hour * 1,
})
if err != nil {
panic(err)
}
r := gin.New()
:
:
}
- Issue a signed token
func Login(c *gin.Context) {
user := "user"
password := "password"
if user == "user" && password == "password" {
// here
token, err := jwt.GetToken(jwt.Claims{
"admin": true,
})
if err != nil {
c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed"})
return
}
c.JSON(http.StatusOK, map[string]interface{}{"token": string(token)})
return
}
c.JSON(http.StatusForbidden, map[string]string{"error": "login failed"})
return
}
- Set the middleware on the route you want to authenticate
func main() {
:
auth := r.Group("/api")
// here
auth.Use(jwt.Verify)
:
}
- Receive private claims
func main() {
:
auth.Use(jwt.Verify)
auth.GET("/hello", func(c *gin.Context) {
// here
claims := jwt.GetClaims(c)
fmt.Println(claims["admin"].(bool)) // true
c.JSON(http.StatusOK, claims)
})
:
}