-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtoken.go
More file actions
62 lines (48 loc) · 1.39 KB
/
token.go
File metadata and controls
62 lines (48 loc) · 1.39 KB
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
package mindsphere
import (
"strings"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/google/uuid"
)
func toX5CFormat(pem string) (formatted string) {
pem = strings.Replace(pem, "-----BEGIN CERTIFICATE-----", "", -1)
pem = strings.Replace(pem, "-----END CERTIFICATE-----", "", -1)
pem = strings.Replace(pem, "\n", "", -1)
return pem
}
// CreateToken creates a JWT for Siemens Mindsphere, valid for 59 minutes.
func CreateToken(clientID, deviceCert, deviceKey, caCert string) (result string, err error) {
devicePrivateKey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(deviceKey))
if err != nil {
return "", err
}
x5c := make([]string, 0, 2)
x5c = append(x5c, toX5CFormat(deviceCert))
x5c = append(x5c, toX5CFormat(caCert))
jtiBytes, err := uuid.NewRandom()
if err != nil {
return "", err
}
jti := jtiBytes.String()
tenBytes, err := uuid.NewRandom()
if err != nil {
return "", err
}
ten := tenBytes.String()
now := time.Now().Unix()
claims := jwt.MapClaims{
"jti": jti,
"iss": clientID,
"sub": clientID,
"aud": []string{"MQTTBroker"},
"iat": time.Now().Unix(),
"exp": now + 60*59, // Expire 59 minutes
"schemas": []string{"urn:siemens:mindsphere:v1"},
"ten": ten,
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
token.Header["x5c"] = x5c
signedJWT, err := token.SignedString(devicePrivateKey)
return signedJWT, nil
}