forked from MicahParks/keyfunc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
48 lines (39 loc) · 1.22 KB
/
main.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
package main
import (
"log"
"github.com/golang-jwt/jwt/v5"
"github.com/pcsysen/keyfunc/v2"
"github.com/pcsysen/keyfunc/v2/examples/custom/method"
)
func main() {
// Declare the custom signing method's key and key ID.
const key = ""
const exampleKID = "exampleKeyID"
// Register the custom signing method.
jwt.RegisterSigningMethod(method.CustomAlgHeader, func() jwt.SigningMethod {
return method.EmptyCustom{}
})
// Create and sign the token using the custom signing method.
unsignedToken := jwt.New(method.EmptyCustom{})
unsignedToken.Header["kid"] = exampleKID
jwtB64, err := unsignedToken.SignedString(key)
if err != nil {
log.Fatalf("Failed to self sign a custom token.\nError: %s.", err.Error())
}
// Create the JWKS from the given signing method's key.
jwks := keyfunc.NewGiven(map[string]keyfunc.GivenKey{
exampleKID: keyfunc.NewGivenCustom(key, keyfunc.GivenKeyOptions{
Algorithm: method.CustomAlgHeader,
}),
})
// Parse the token.
token, err := jwt.Parse(jwtB64, jwks.Keyfunc)
if err != nil {
log.Fatalf("Failed to parse the JWT.\nError: %s", err.Error())
}
// Check if the token is valid.
if !token.Valid {
log.Fatalf("The token is not valid.")
}
log.Println("The token is valid.")
}