1 Star 0 Fork 0

carlmax_my/console-core-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
util.go 2.15 KB
一键复制 编辑 原始数据 按行查看 历史
carlmax_my 提交于 2024-12-02 21:32 . init project
package jwt
import (
"errors"
"fmt"
"log"
"time"
"github.com/golang-jwt/jwt/v5"
)
func GetClaimsString(claims jwt.MapClaims, key string) string {
if subject, ok := claims[key]; ok {
if value, ok := subject.(string); ok {
return value
}
}
return ""
}
func GetClaimsStringPtr(claims jwt.MapClaims, key string) *string {
if subject, ok := claims[key]; ok {
if value, ok := subject.(string); ok {
return &value
}
}
return nil
}
func GetClaimsInt64Ptr(claims jwt.MapClaims, key string) *int64 {
if subject, ok := claims[key]; ok {
if value, ok := subject.(int64); ok {
return &value
}
}
return nil
}
func GetClaimsIssuerAndExpiresAt2(claims jwt.MapClaims) (issuer *string, expiresAt *jwt.NumericDate) {
issuer = GetClaimsStringPtr(claims, "iss")
exp := GetClaimsInt64Ptr(claims, "exp")
if exp != nil {
expiresAt = jwt.NewNumericDate(time.Unix(*exp, 0))
}
return
}
func GetClaimsIssuerAndExpiresAt(claims jwt.Claims) (issuer *string, expiresAt *jwt.NumericDate) {
mapClaims, _ := claims.(jwt.MapClaims)
return GetClaimsIssuerAndExpiresAt2(mapClaims)
}
func ParseJwtToken(jwtToken *string, secret string) (jwt.Claims, error) {
token, err := jwt.Parse(*jwtToken, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method %v", token.Header["alg"])
}
return []byte(secret), nil
})
if err != nil {
log.Println("jwt parse err:", err)
return nil, err
}
if token.Valid {
return token.Claims, nil
}
return nil, errors.New("invalid jwt token")
}
// self jwt token, no need to check activated
func ParseJwtTokenWithClaims(jwtToken *string, secret string) (*CustomClaims, error) {
claims := &CustomClaims{}
token, err := jwt.ParseWithClaims(*jwtToken, claims, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method %v", token.Header["alg"])
}
return []byte(secret), nil
})
if err != nil {
return nil, err // token is expired by
}
if !token.Valid {
return nil, errors.New("invalid jwt")
}
// if token.Claims.Valid().Error()
return claims, nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/carlmax_my/console-core-go.git
git@gitee.com:carlmax_my/console-core-go.git
carlmax_my
console-core-go
console-core-go
v0.0.1

搜索帮助

0d507c66 1850385 C8b1a773 1850385