Skip to content

Commit a2eb592

Browse files
authored
refactor(api): derive JWT public key from private key (#513)
refactor(api): derive JWT public key from privat
1 parent 44a20dd commit a2eb592

2 files changed

Lines changed: 27 additions & 8 deletions

File tree

api/mw/token.go

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,13 @@ limitations under the License.
1717
package mw
1818

1919
import (
20+
"crypto"
21+
"crypto/ed25519"
22+
"crypto/x509"
23+
"encoding/pem"
2024
"errors"
2125
"fmt"
26+
"sync"
2227
"time"
2328

2429
"github.com/golang-jwt/jwt/v4"
@@ -108,17 +113,17 @@ func CheckToken(token string) (int64, string, error) {
108113
return -1, "", errno.AuthError.WithMessage("cannot handle claims")
109114
}
110115

111-
secret, err := jwt.ParseEdPublicKeyFromPEM([]byte(constants.PublicKey))
116+
publicKey, err := getPublicKey()
112117
if err != nil {
113-
return -1, "", errno.AuthError.WithMessage(fmt.Sprintf("parse public key failed, err: %v", err))
118+
return -1, "", errno.AuthError.WithMessage(fmt.Sprintf("get public key failed, err: %v", err))
114119
}
115120

116121
// 使用正确的密钥再次解析 token
117122
response, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
118123
if _, ok := token.Method.(*jwt.SigningMethodEd25519); !ok {
119124
return nil, errno.AuthError.WithMessage(fmt.Sprintf("unexpected signing method: %v", token.Header["alg"]))
120125
}
121-
return secret, nil
126+
return publicKey, nil
122127
})
123128
// 验证 token 是否有效
124129
if err != nil {
@@ -145,3 +150,22 @@ func checkError(err error, tokenType int64) error {
145150
}
146151
return errno.AuthError.WithMessage(err.Error())
147152
}
153+
154+
var getPublicKey = sync.OnceValues(func() (crypto.PublicKey, error) {
155+
block, _ := pem.Decode([]byte(config.Server.Secret))
156+
if block == nil {
157+
return nil, fmt.Errorf("failed to decode PEM block")
158+
}
159+
160+
keyAny, err := x509.ParsePKCS8PrivateKey(block.Bytes)
161+
if err != nil {
162+
return nil, fmt.Errorf("failed to parse PKCS8 private key: %w", err)
163+
}
164+
165+
privateKey, ok := keyAny.(ed25519.PrivateKey)
166+
if !ok {
167+
return nil, fmt.Errorf("key is not ed25519 private key")
168+
}
169+
170+
return privateKey.Public(), nil
171+
})

pkg/constants/token.go

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ limitations under the License.
1717
package constants
1818

1919
import (
20-
"fmt"
2120
"time"
2221
)
2322

@@ -37,7 +36,3 @@ const (
3736

3837
StuIDContextKey = "stu_id" // 从context 中获取 stu_id
3938
)
40-
41-
var PublicKey = fmt.Sprintf("%v\n%v\n%v", "-----BEGIN PUBLIC KEY-----",
42-
"MCowBQYDK2VwAyEAT+ypuz7wIltf8HoFUEI/rDBrQNhZShqLv88j4aAWnT0=",
43-
"-----END PUBLIC KEY-----")

0 commit comments

Comments
 (0)