homepage/webserver/authmod/jwt.go

51 lines
1.0 KiB
Go
Raw Normal View History

2022-12-26 05:48:30 +00:00
package authmod
import (
"time"
"github.com/coreos/go-oidc"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
)
type AuthTokenClaims struct {
jwt.RegisteredClaims // 표준 토큰 Claims
UserInfo *oidc.UserInfo
}
var TknHmacSecret []byte = nil
func init() {
TknHmacSecret = []byte(uuid.New().String())
}
func IssueJWT(userInfo *oidc.UserInfo, period time.Duration) (string, error) {
claims := AuthTokenClaims{
UserInfo: userInfo,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(period)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
},
}
tkn := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := tkn.SignedString([]byte(TknHmacSecret))
return ss, err
}
func ParseJWTwithClaims(ss string) (*AuthTokenClaims, error) {
claims := AuthTokenClaims{}
_, err := jwt.ParseWithClaims(ss, &claims, func(token *jwt.Token) (interface{}, error) {
return TknHmacSecret, nil
})
if err != nil {
return nil, err
}
return &claims, nil
}