1 Star 0 Fork 0

qhitc / grpcwebserver

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
jwthelper.go 1.78 KB
一键复制 编辑 原始数据 按行查看 历史
qhitc 提交于 2023-05-29 10:06 . 创建提交
package jwthelper
import (
"context"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
type CustomClaims struct {
jwt.StandardClaims
Username string `json:"username,omitempty"`
Roles string `json:"roles,omitempty"`
}
func CreateJWT(jwtSecret, username, roles string, expires int64) (string, error) {
claims := &CustomClaims{
StandardClaims: jwt.StandardClaims{
ExpiresAt: expires,
IssuedAt: time.Now().Unix(),
Issuer: "greeter",
},
Username: username,
Roles: roles,
}
// Create token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Generate encoded token and send it as response.
t, err := token.SignedString([]byte(jwtSecret))
if err != nil {
return "", err
}
return string(t), nil
}
func GetClaimsFromContext(jwtSecret string, ctx context.Context) (*CustomClaims, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.Errorf(codes.Unauthenticated, "no metadata, can't identify")
}
authHeader := md["authorization"]
if len(authHeader) == 0 {
return nil, status.Errorf(codes.Unauthenticated, "no authorization key, can't identify")
}
bearerToken := authHeader[0]
tokenStr := strings.Join(strings.Split(bearerToken, " ")[1:], " ")
token, err := jwt.ParseWithClaims(tokenStr, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(jwtSecret), nil
})
if err != nil {
//log.Println(err)
return nil, status.Errorf(codes.Unauthenticated, "no authorization key", err.Error())
}
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
return claims, nil
} else {
//log.Println(err)
return nil, status.Errorf(codes.Unauthenticated, "no authorization key", err.Error())
}
}
1
https://gitee.com/qhitc_admin/grpcwebserver.git
git@gitee.com:qhitc_admin/grpcwebserver.git
qhitc_admin
grpcwebserver
grpcwebserver
dc0fecf8d0e2

搜索帮助