Skip to content
This repository has been archived by the owner on May 21, 2022. It is now read-only.

Add example custom implementation jwt-go #466

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
## Example Implementation JWT GO

### Example JWT Sign

```go
package main

import (
"fmt"

"github.com/sirupsen/logrus"
)

// example usage
func main() {

userData := map[string]interface{}{"id": 1, "email": "[email protected]"}
accessToken, errToken := util.Sign(userData, "JWT_SECRET", 5) // data -> secretkey env name -> expireAt

if errToken != nil {
logrus.Fatal(errToken.Error())
}

fmt.Println("my accessToken here", accessToken)
}
```

### Example JWT Verify

```go
package main

import (
"fmt"

"github.com/sirupsen/logrus"
)

// example usage
func main() {

userData := map[string]interface{}{"id": 1, "email": "[email protected]"}
accessToken, errToken := util.Sign(userData, "JWT_SECRET", 5) // data -> secretkey env name -> expireAt

if errToken != nil {
logrus.Fatal(errToken.Error())
}

verifiedToken, errTokenVerified := util.VerifyToken(accessToken, "JWT_SECRET")

if errTokenVerified != nil {
logrus.Fatal(errTokenVerified.Error())
}

fmt.Println("my verified accessToken here", verifiedToken)
}
```

### Example JWT Decoded

```go
package main

import (
"fmt"

"github.com/sirupsen/logrus"
)

// example usage
func main() {

userData := map[string]interface{}{"id": 1, "email": "[email protected]"}
accessToken, errToken := util.Sign(userData, "JWT_SECRET", 5) // data -> secretkey env name -> expireAt

if errToken != nil {
logrus.Fatal(errToken.Error())
}

verifiedToken, errTokenVerified := util.VerifyToken(accessToken, "JWT_SECRET")

if errTokenVerified != nil {
logrus.Fatal(errTokenVerified.Error())
}

decodedToken := util.DecodedToken(verifiedToken)

fmt.Println("my decoded accessToken here", decodedToken.Claims.Email)
}
```
10 changes: 10 additions & 0 deletions example/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module example-jwt

go 1.16

require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gin-gonic/gin v1.7.1
github.com/joho/godotenv v1.3.0
github.com/sirupsen/logrus v1.8.1
)
57 changes: 57 additions & 0 deletions example/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.7.1 h1:qC89GU3p8TvKWMAVhEpmpB2CIb1hnqt2UdKZaP93mS8=
github.com/gin-gonic/gin v1.7.1/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no=
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc=
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
21 changes: 21 additions & 0 deletions example/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package main

import (
"fmt"

"github.com/sirupsen/logrus"
)

// example usage
func main() {

secretKey := util.GodotEnv("JWT_SECRET")
userData := map[string]interface{}{"id": 1, "email": "[email protected]"}
accessToken, errToken := util.Sign(userData, secretKey, 5) // data -> secretkey -> expireAt

if errToken != nil {
logrus.Fatal(errToken.Error())
}

fmt.Println("my accessToken here", accessToken)
}
20 changes: 20 additions & 0 deletions example/utils/dotenv.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package util

import (
"os"

"github.com/joho/godotenv"
)

func GodotEnv(key string) string {
env := make(chan string, 1)

if os.Getenv("GO_ENV") != "production" {
godotenv.Load(".env")
env <- os.Getenv(key)
} else {
env <- os.Getenv(key)
}

return <-env
}
73 changes: 73 additions & 0 deletions example/utils/jwt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package util

import (
"encoding/json"
"time"

"github.com/dgrijalva/jwt-go"
"github.com/sirupsen/logrus"
)

// metadata for your application, change this for your app
type MetaToken struct {
ID int
Email string
ExpiredAt time.Time
Authorization bool
}

type AccessToken struct {
Claims MetaToken
}

// created accessToken like jwt.sign in javascript
func SignToken(Data map[string]interface{}, SecrePublicKeyEnvName string, ExpiredAt time.Duration) (string, error) {

expiredAt := time.Now().Add(time.Duration(time.Second) * ExpiredAt).Unix()

jwtSecretKey := GodotEnv(SecrePublicKeyEnvName)

claims := jwt.MapClaims{}
claims["expiredAt"] = expiredAt
claims["authorization"] = true

for i, v := range Data {
claims[i] = v
}

to := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
accessToken, err := to.SignedString([]byte(jwtSecretKey))

if err != nil {
logrus.Error(err.Error())
return accessToken, err
}

return accessToken, nil
}

// verified accessToken like jwt.verify in javascript
func VerifyToken(accessToken, SecrePublicKeyEnvName string) (*jwt.Token, error) {

jwtSecretKey := GodotEnv(SecrePublicKeyEnvName)

token, err := jwt.Parse(accessToken, func(token *jwt.Token) (interface{}, error) {
return []byte(jwtSecretKey), nil
})

if err != nil {
logrus.Error(err.Error())
return nil, err
}

return token, nil
}

// decode accessToken like jwt.decode in javascript
func DecodeToken(accessToken *jwt.Token) AccessToken {
var token AccessToken
stringify, _ := json.Marshal(&accessToken)
json.Unmarshal([]byte(stringify), &token)

return token
}