/
jwt.go
53 lines (38 loc) · 1.22 KB
/
jwt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package jwt
import (
"fmt"
"log"
"idp/models/util"
"io/ioutil"
"github.com/labstack/echo"
"github.com/dgrijalva/jwt-go"
)
// Sign returns jwt token string
func Sign(claims map[string]interface{}) (string, error) {
log.Println("JWT SIGN START")
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims(claims))
log.Println(token)
key, err := ioutil.ReadFile(util.GetAbsPath("/keystore/id_rsa"))
priv, _ := jwt.ParseRSAPrivateKeyFromPEM(key)
tokenString, err := token.SignedString(priv)
return tokenString, err
}
// Verify returns the payload and is valid
func Verify(tokenString string) bool {
key, _ := ioutil.ReadFile(util.GetAbsPath("/keystore/id_rsa.pub"))
pub, _ := jwt.ParseRSAPublicKeyFromPEM(key)
token, _ := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("%v", token.Header["alg"])
}
return pub, nil
})
if _, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return ok
}
return false
}
// DecodeContext will decode context and return the value by key
func DecodeContext(c echo.Context, key string) interface{} {
return c.Get("IDHub").(*jwt.Token).Claims.(jwt.MapClaims)[key]
}