-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhmac_verify_claims.go
77 lines (59 loc) · 1.69 KB
/
hmac_verify_claims.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"fmt"
"github.com/golang-jwt/jwt"
"time"
)
func main() {
var mySigningKey = []byte("hello gophers!!!")
// user api
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["aud"] = "238d4793-70de-4183-9707-48ed8ecd19d9"
claims["sub"] = "19016b73-3ffa-4b26-80d8-aa9287738677"
claims["iss"] = "fusionauth.io"
claims["exp"] = time.Now().Add(time.Minute * 5).Unix()
claims["name"] = "Dan Moore"
var roles [2]string
roles[0] = "RETRIEVE_TODOS"
roles[1] = "WRITE_TODOS"
claims["roles"] = roles
tokenString, err := token.SignedString(mySigningKey)
if err != nil {
fmt.Println(fmt.Errorf("Something Went Wrong: %s", err.Error()))
}
fmt.Println(string(tokenString))
// todo api
decodedToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return mySigningKey, nil
})
if err != nil {
fmt.Printf("Something Went Wrong: %s", err.Error())
return
}
if claims, ok := decodedToken.Claims.(jwt.MapClaims); ok && decodedToken.Valid {
// Valid looks at time based claims
// now check other claims
expectedAud := "238d4793-70de-4183-9707-48ed8ecd19d9"
checkAudience := claims.VerifyAudience(expectedAud, true)
if !checkAudience {
fmt.Println("invalid aud")
return
}
// verify iss claim
expectedIss := "fusionauth.io"
checkIss := claims.VerifyIssuer(expectedIss, true)
if !checkIss {
fmt.Println("invalid iss")
return
}
} else {
fmt.Println(err)
return
}
fmt.Println("")
fmt.Printf("%+v\n", decodedToken.Claims)
}