add geneate jwt
This commit is contained in:
parent
6cb3d5ce45
commit
3fe321f358
@ -5,9 +5,17 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"github.com/dgrijalva/jwt-go"
|
"github.com/dgrijalva/jwt-go"
|
||||||
"os"
|
"os"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var publicKey = strings.Replace(`-----BEGIN PUBLIC KEY-----
|
||||||
|
MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgHgnvr7O2tiApjJfid1orFnIGm69
|
||||||
|
80fZp+Lpbjo+NC/0whMFga2Biw5b1G2Q/B2u0tpO1Fs/E8z7Lv1nYfr5jx2S8x6B
|
||||||
|
dA4TS2kB9Kf0wn0+7wSlyikHoKhbtzwXHZl17GsyEi6wHnsqNBSauyIWhpha8i+Y
|
||||||
|
+3GyaOY536H47qyXAgMBAAE=
|
||||||
|
-----END PUBLIC KEY-----`, "\t", "", -1)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
DefaultAccessSecret = "awesomeAC"
|
DefaultAccessSecret = "awesomeAC"
|
||||||
DefaultHeaderKey = "Authorization"
|
DefaultHeaderKey = "Authorization"
|
||||||
@ -15,7 +23,7 @@ const (
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
//_ cookie.Cookie = new(JwtAdapter)
|
//_ cookie.Cookie = new(JwtAdapter)
|
||||||
accessSecret = DefaultAccessSecret
|
accessSecret = publicKey
|
||||||
)
|
)
|
||||||
|
|
||||||
type JwtAdapter struct {
|
type JwtAdapter struct {
|
||||||
@ -91,3 +99,35 @@ func Decode(tokenString string) (*JwtAdapter, error) {
|
|||||||
func Timestamp() int64 {
|
func Timestamp() int64 {
|
||||||
return time.Now().UnixNano() / int64(time.Millisecond)
|
return time.Now().UnixNano() / int64(time.Millisecond)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ForCreate struct {
|
||||||
|
PrivateKey []byte
|
||||||
|
PublicKey []byte
|
||||||
|
Algorithm *jwt.SigningMethodRSA
|
||||||
|
ExpiresIn time.Duration
|
||||||
|
Issuer string
|
||||||
|
Audience string
|
||||||
|
}
|
||||||
|
|
||||||
|
func Create(id string, forCreate ForCreate) (string, error) {
|
||||||
|
privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(forCreate.PrivateKey)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to parse private key: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UTC()
|
||||||
|
|
||||||
|
claims := jwt.MapClaims{
|
||||||
|
"id": id,
|
||||||
|
"exp": now.Add(forCreate.ExpiresIn).Unix(),
|
||||||
|
"aud": forCreate.Audience,
|
||||||
|
"iss": forCreate.Issuer,
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := jwt.NewWithClaims(forCreate.Algorithm, claims).SignedString(privateKey)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed create jwt: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user