add jwt parser

This commit is contained in:
daniel.w 2024-08-27 13:49:17 +08:00
parent 2a933425d7
commit 30bff1e64b
7 changed files with 26 additions and 9 deletions

View File

@ -4,4 +4,5 @@ use (
./errors
./validator
./worker_pool
./jwt
)

View File

@ -5,7 +5,7 @@ type DataClaims map[string]string
const (
idCode = "id"
roleCode = "role"
deviceIdCode = "device_id"
deviceIDCode = "device_id"
scopeCode = "scope"
uidCode = "uid"
)
@ -26,7 +26,7 @@ func (c DataClaims) SetRole(role string) {
}
func (c DataClaims) SetDeviceID(deviceID string) {
c.Set(deviceIdCode, deviceID)
c.Set(deviceIDCode, deviceID)
}
func (c DataClaims) SetScope(scope string) {
@ -43,6 +43,7 @@ func (c DataClaims) Get(key string) string {
if val, ok := c[key]; ok {
return val
}
return ""
}
@ -59,7 +60,7 @@ func (c DataClaims) ID() string {
}
func (c DataClaims) DeviceID() string {
return c.Get(deviceIdCode)
return c.Get(deviceIDCode)
}
func (c DataClaims) UID() string {

View File

@ -1,8 +1,9 @@
package jwt
import (
"github.com/stretchr/testify/require"
"testing"
"github.com/stretchr/testify/require"
)
func TestDataClaimsSettersAndGetters(t *testing.T) {

View File

@ -1,8 +1,9 @@
package jwt
import (
"github.com/golang-jwt/jwt/v4"
"time"
"github.com/golang-jwt/jwt/v4"
)
type Token struct {

View File

@ -1,9 +1,10 @@
package jwt
import (
"github.com/stretchr/testify/require"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestAccessTokenExpires(t *testing.T) {

View File

@ -2,4 +2,13 @@ module code.30cm.net/digimon/library-go/jwt
go 1.22.3
require github.com/golang-jwt/jwt/v4 v4.5.0
require (
github.com/golang-jwt/jwt/v4 v4.5.0
github.com/stretchr/testify v1.9.0
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

View File

@ -2,8 +2,9 @@ package jwt
import (
"fmt"
"github.com/golang-jwt/jwt/v4"
"time"
"github.com/golang-jwt/jwt/v4"
)
func GenerateAccessToken(token Token, data any, sign string, issuer string) (string, error) {
@ -35,6 +36,7 @@ func ParseToken(accessToken string, secret string, validate bool) (jwt.MapClaims
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("token unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret), nil
})
if err != nil {
@ -42,7 +44,7 @@ func ParseToken(accessToken string, secret string, validate bool) (jwt.MapClaims
}
} else {
parser := jwt.NewParser(jwt.WithoutClaimsValidation())
token, err = parser.Parse(accessToken, func(token *jwt.Token) (interface{}, error) {
token, err = parser.Parse(accessToken, func(_ *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil {
@ -84,5 +86,6 @@ func convertMap(input map[string]interface{}) map[string]string {
output[key] = fmt.Sprintf("%v", value)
}
}
return output
}