added claims type

This commit is contained in:
ston1th 2018-09-12 23:14:09 +02:00
commit 6e61945c2c
3 changed files with 64 additions and 8 deletions

52
claims.go Normal file
View file

@ -0,0 +1,52 @@
// Copyright (C) 2018 Marius Schellenberger
package jwt
// Claims is the claim type of the token
type Claims map[string]interface{}
// Get returns a value from the claims map
func (c Claims) Get(key string) (v interface{}, ok bool) {
v, ok = c[key]
return
}
// GetString returns a string from the claims map
func (c Claims) GetString(key string) (s string) {
if v, ok := c.Get(key); ok && v != nil {
s, _ = v.(string)
}
return
}
// GetBool returns a bool from the claims map
func (c Claims) GetBool(key string) (b bool) {
if v, ok := c.Get(key); ok && v != nil {
b, _ = v.(bool)
}
return
}
// GetInt returns an int from the claims map
func (c Claims) GetInt(key string) (i int) {
if v, ok := c.Get(key); ok && v != nil {
i, _ = v.(int)
}
return
}
// GetFloat returns a float from the claims map
func (c Claims) GetFloat(key string) (f float64) {
if v, ok := c.Get(key); ok && v != nil {
f, _ = v.(float64)
}
return
}
// Set sets the value of key in the claims map, if not nil
func (c Claims) Set(key string, v interface{}) {
if c == nil {
return
}
c[key] = v
}

16
jwt.go
View file

@ -323,7 +323,7 @@ type Token struct {
signature string
rawSignature []byte
header map[string]interface{}
Claims map[string]interface{}
Claims Claims
}
// String returns the tokens encoded string
@ -352,14 +352,18 @@ func (t *Token) Data() string {
}
// NewToken returns a new *Token using the provided hash algorithm and claims
// If h is nil HS256 will be used
func NewToken(claims map[string]interface{}, h Hash) *Token {
if h == nil {
h = NewHS256()
// If claims is nil, an empty map is used
// If hash is nil, HS256 is used
func NewToken(claims Claims, hash Hash) *Token {
if claims == nil {
claims = make(Claims)
}
if hash == nil {
hash = NewHS256()
}
return &Token{
header: map[string]interface{}{
"alg": h.Alg(),
"alg": hash.Alg(),
"typ": typ,
},
Claims: claims,

View file

@ -14,7 +14,7 @@ func TestValidate(t *testing.T) {
if err != nil {
t.Error(err)
}
token := NewToken(map[string]interface{}{
token := NewToken(Claims{
"sub": "1234567890",
"name": "John Doe",
"admin": true,
@ -65,7 +65,7 @@ func TestNoBlacklist(t *testing.T) {
if err != nil {
t.Error(err)
}
token := NewToken(map[string]interface{}{
token := NewToken(Claims{
"sub": "1234567890",
"name": "John Doe",
"admin": true,