Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ken109/gin-jwt
Very easy to use jwt with gin framework.
https://github.com/ken109/gin-jwt
gin go golang jwt
Last synced: about 1 month ago
JSON representation
Very easy to use jwt with gin framework.
- Host: GitHub
- URL: https://github.com/ken109/gin-jwt
- Owner: ken109
- License: mit
- Created: 2021-02-01T01:44:58.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2023-11-23T05:36:28.000Z (12 months ago)
- Last Synced: 2024-10-01T01:01:54.389Z (about 2 months ago)
- Topics: gin, go, golang, jwt
- Language: Go
- Homepage:
- Size: 60.5 KB
- Stars: 2
- Watchers: 1
- Forks: 4
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Overview
1. Issue private key
```bash
openssl genrsa -out private.key 2048
```2. Example main.go
```go
package mainimport (
"github.com/gin-gonic/gin"
"github.com/ken109/gin-jwt"
"fmt"
"net/http"
)const MyRealm = "my-realm"
func main() {
// setup
_ = jwt.SetUp(
jwt.Option{
Realm: MyRealm,
SigningAlgorithm: jwt.RS256,
PrivKeyFile: "private.key",
},
)r := gin.New()
r.POST("/login", Login)
r.GET("/refresh", RefreshToken)auth := r.Group("/api")
// Set the middleware on the route you want to authenticate
auth.Use(jwt.MustVerify(MyRealm))auth.GET(
"/hello", func(c *gin.Context) {
claims := jwt.GetClaims(c)fmt.Println(claims["admin"].(bool)) // true
c.JSON(http.StatusOK, claims)
},
)if err := r.Run(":8080"); err != nil {
panic(err)
}
}func Login(c *gin.Context) {
password := "test"if password != "test" {
c.JSON(http.StatusForbidden, "login failed")
return
} else {
// Issue Token
token, refreshToken, _ := jwt.IssueToken(
MyRealm,
jwt.Claims{
"admin": true,
},
)c.JSON(
http.StatusOK, gin.H{
"token": token,
"refresh_token": refreshToken,
},
)
}
}func RefreshToken(c *gin.Context) {
ok, token, refreshToken, _ := jwt.RefreshToken(MyRealm, c.Query("refresh_token"))
if !ok {
c.Status(http.StatusUnauthorized)
return
}c.JSON(
http.StatusOK, gin.H{
"token": token,
"refresh_token": refreshToken,
},
)
}
```