-
Notifications
You must be signed in to change notification settings - Fork 1
/
jwt-go-ecdsa.go
94 lines (79 loc) · 2.49 KB
/
jwt-go-ecdsa.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"time"
"github.com/golang-jwt/jwt/v5"
)
func GenerateToken(policyPath string, serviceName string, purpose string, keyPath string, expirationInHours time.Duration) (string, error) {
// Load policy from file
policyData, err := ioutil.ReadFile(policyPath)
if err != nil {
log.Fatalf("Error reading policy.json: %v", err)
}
// Parse the policy JSON into a map
var policyMap map[string]interface{}
err = json.Unmarshal(policyData, &policyMap)
if err != nil {
log.Fatalf("Error parsing policy.json: %v", err)
}
// Retrieve the services object from the policy
servicesObj, exists := policyMap["services"].(map[string]interface{})
if !exists {
return "", fmt.Errorf("Invalid policy format: services not found")
}
// Get the service policy based on the service name
servicePolicy, exists := servicesObj[serviceName].(map[string]interface{})
if !exists {
return "", fmt.Errorf("Service %s not found in policy file", serviceName)
}
// Get the policy for the specified purpose
purposePolicy, exists := servicePolicy[purpose].(map[string]interface{})
if !exists {
return "", fmt.Errorf("Purpose %s not found in service policy", purpose)
}
// Create the reduced policy based on the purpose policy
reducedPolicy := map[string]interface{}{
"allowed": purposePolicy["allowed"],
"generalized": purposePolicy["generalized"],
"noised": purposePolicy["noised"],
"reduced": purposePolicy["reduced"],
}
// Convert the reduced policy to JSON
reducedPolicyJSON, err := json.Marshal(reducedPolicy)
if err != nil {
log.Fatalf("Error marshaling reduced policy: %v", err)
}
// Load the RSA private key from file
keyData, err := ioutil.ReadFile(keyPath)
if err != nil {
log.Fatalf("Error reading private key: %v", err)
}
// Parse the RSA private key
privateKey, err := jwt.ParseECPrivateKeyFromPEM(keyData)
if err != nil {
log.Fatalf("Error parsing private key: %v", err)
}
// Create the Claims
claims := struct {
Policy json.RawMessage `json:"policy"`
jwt.RegisteredClaims
}{
reducedPolicyJSON,
jwt.RegisteredClaims{
// Valid for 2 hrs
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * expirationInHours)),
Issuer: "tokenGenerator",
},
}
// Sign the token using ECDSA-256
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
tokenString, err := token.SignedString(privateKey)
if err != nil {
log.Fatalf("Error signing token: %v", err)
return "", err
}
return tokenString, nil
}