mirror of
https://github.com/lejianwen/rustdesk-api.git
synced 2025-12-03 10:33:18 +00:00
feat!: Add JWT
- `RUSTDESK_API_JWT_KEY`如果设置,将会启用JWT,token自动续期功能将失效 - 此功能是为了server端校验token的合法性
This commit is contained in:
@@ -1,14 +1,13 @@
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
"fmt"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Jwt struct {
|
||||
privateKey *rsa.PrivateKey
|
||||
Key []byte
|
||||
TokenExpireDuration time.Duration
|
||||
}
|
||||
|
||||
@@ -17,31 +16,24 @@ type UserClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func NewJwt(privateKeyFile string, tokenExpireDuration time.Duration) *Jwt {
|
||||
privateKeyContent, err := os.ReadFile(privateKeyFile)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(privateKeyContent)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
func NewJwt(key string, tokenExpireDuration time.Duration) *Jwt {
|
||||
return &Jwt{
|
||||
privateKey: privateKey,
|
||||
Key: []byte(key),
|
||||
TokenExpireDuration: tokenExpireDuration,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Jwt) GenerateToken(userId uint) string {
|
||||
t := jwt.NewWithClaims(jwt.SigningMethodRS256,
|
||||
t := jwt.NewWithClaims(jwt.SigningMethodHS256,
|
||||
UserClaims{
|
||||
UserId: userId,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(s.TokenExpireDuration)),
|
||||
},
|
||||
})
|
||||
token, err := t.SignedString(s.privateKey)
|
||||
token, err := t.SignedString(s.Key)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return ""
|
||||
}
|
||||
return token
|
||||
@@ -49,7 +41,7 @@ func (s *Jwt) GenerateToken(userId uint) string {
|
||||
|
||||
func (s *Jwt) ParseToken(tokenString string) (uint, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return s.privateKey.Public(), nil
|
||||
return s.Key, nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
|
||||
Reference in New Issue
Block a user