package jwt
import "github.com/square/go-jose/jwt"
Index ¶
- Constants
- Variables
- type Audience
- type Builder
- type Claims
- func (c Claims) Validate(e Expected) error
- func (c Claims) ValidateWithLeeway(e Expected, leeway time.Duration) error
- type Expected
- type JSONWebToken
- func ParseEncrypted(s string) (*JSONWebToken, error)
- func ParseSigned(s string) (*JSONWebToken, error)
- func (t *JSONWebToken) Claims(key interface{}, dest ...interface{}) error
- type NumericDate
Examples ¶
- Claims.Validate
- Claims.Validate (WithParse)
- Encrypted
- JSONWebToken.Claims (Map)
- JSONWebToken.Claims (Multiple)
- ParseEncrypted
- ParseSigned
- Signed
- Signed (MultipleClaims)
Constants ¶
const ( // DefaultLeeway defines the default leeway for matching NotBefore/Expiry claims. DefaultLeeway = 1.0 * time.Minute )
Variables ¶
ErrExpired indicates that token is used after expiry time indicated in exp claim.
var ErrInvalidAudience = errors.New("square/go-jose/jwt: validation failed, invalid audience claim (aud)")
ErrInvalidAudience indicated invalid aud claim.
var ErrInvalidClaims = errors.New("square/go-jose/jwt: expected claims to be value convertible into JSON object")
ErrInvalidClaims indicates that given claims have invalid type.
ErrInvalidID indicates invalid jti claim.
var ErrInvalidIssuer = errors.New("square/go-jose/jwt: validation failed, invalid issuer claim (iss)")
ErrInvalidIssuer indicates invalid iss claim.
var ErrInvalidSubject = errors.New("square/go-jose/jwt: validation failed, invalid subject claim (sub)")
ErrInvalidSubject indicates invalid sub claim.
ErrNotValidYet indicates that token is used before time indicated in nbf claim.
var ErrUnmarshalAudience = errors.New("square/go-jose/jwt: expected string or array value to unmarshal to Audience")
ErrUnmarshalAudience indicates that aud claim could not be unmarshalled.
var ErrUnmarshalNumericDate = errors.New("square/go-jose/jwt: expected number value to unmarshal NumericDate")
ErrUnmarshalNumericDate indicates that JWT NumericDate could not be unmarshalled.
Types ¶
type Audience ¶
type Audience []string
Audience represents the recipents that the token is intended for.
func (Audience) Contains ¶
func (*Audience) UnmarshalJSON ¶
UnmarshalJSON reads an audience from its JSON representation.
type Builder ¶
type Builder interface { // Claims encodes claims into JWE/JWS form. Multiple calls will merge claims // into single JSON object. Claims(i interface{}) Builder // Token builds a JSONWebToken from provided data. Token() (*JSONWebToken, error) // FullSerialize serializes a token using the full serialization format. FullSerialize() (string, error) // CompactSerialize serializes a token using the compact serialization format. CompactSerialize() (string, error) }
Builder is a utility for making JSON Web Tokens. Calls can be chained, and errors are accumulated until the final call to CompactSerialize/FullSerialize.
func Encrypted ¶
func Encrypted(enc jose.Encrypter) Builder
Encrypted creates builder for encrypted tokens.
Code:
Example¶
{
enc, err := jose.NewEncrypter(jose.A128GCM, jose.Recipient{Algorithm: jose.DIRECT, Key: sharedEncryptionKey}, nil)
if err != nil {
panic(err)
}
cl := jwt.Claims{
Subject: "subject",
Issuer: "issuer",
}
raw, err := jwt.Encrypted(enc).Claims(cl).CompactSerialize()
if err != nil {
panic(err)
}
fmt.Println(raw)
}
func Signed ¶
func Signed(sig jose.Signer) Builder
Signed creates builder for signed tokens.
Code:
Output: Code:
Output:Example¶
{
key := []byte("secret")
sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: key}, &jose.SignerOptions{})
if err != nil {
panic(err)
}
cl := jwt.Claims{
Subject: "subject",
Issuer: "issuer",
NotBefore: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)),
Audience: jwt.Audience{"leela", "fry"},
}
raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
if err != nil {
panic(err)
}
fmt.Println(raw)
// Output: eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOlsibGVlbGEiLCJmcnkiXSwiaXNzIjoiaXNzdWVyIiwibmJmIjoxLjQ1MTYwNjRlKzA5LCJzdWIiOiJzdWJqZWN0In0.uazfxZNgnlLdNDK7JkuYj3LlT4jSyEDG8EWISBPUuME
}
eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOlsibGVlbGEiLCJmcnkiXSwiaXNzIjoiaXNzdWVyIiwibmJmIjoxLjQ1MTYwNjRlKzA5LCJzdWIiOiJzdWJqZWN0In0.uazfxZNgnlLdNDK7JkuYj3LlT4jSyEDG8EWISBPUuME
Example (MultipleClaims)¶
{
c := &jwt.Claims{
Subject: "subject",
Issuer: "issuer",
}
c2 := struct {
Scopes []string
}{
[]string{"foo", "bar"},
}
raw, err := jwt.Signed(signer).Claims(c).Claims(c2).CompactSerialize()
if err != nil {
panic(err)
}
fmt.Println(raw)
// Output: eyJhbGciOiJIUzI1NiJ9.eyJTY29wZXMiOlsiZm9vIiwiYmFyIl0sImlzcyI6Imlzc3VlciIsInN1YiI6InN1YmplY3QifQ.esKOIsmwkudr_gnfnB4SngxIr-7pspd5XzG3PImfQ6Y
}
eyJhbGciOiJIUzI1NiJ9.eyJTY29wZXMiOlsiZm9vIiwiYmFyIl0sImlzcyI6Imlzc3VlciIsInN1YiI6InN1YmplY3QifQ.esKOIsmwkudr_gnfnB4SngxIr-7pspd5XzG3PImfQ6Y
type Claims ¶
type Claims struct { Issuer string `json:"iss,omitempty"` Subject string `json:"sub,omitempty"` Audience Audience `json:"aud,omitempty"` Expiry NumericDate `json:"exp,omitempty"` NotBefore NumericDate `json:"nbf,omitempty"` IssuedAt NumericDate `json:"iat,omitempty"` ID string `json:"jti,omitempty"` }
Claims represents public claim values (as specified in RFC 7519).
func (Claims) Validate ¶
Validate checks claims in a token against expected values.
A default leeway value of one minute is used to compare time values.
Code:play
Output: Code:play
Output:Example¶
package main
import (
"fmt"
"time"
"gopkg.in/square/go-jose.v2/jwt"
)
func main() {
cl := jwt.Claims{
Subject: "subject",
Issuer: "issuer",
NotBefore: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)),
Expiry: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 15, 0, 0, time.UTC)),
Audience: jwt.Audience{"leela", "fry"},
}
err := cl.Validate(jwt.Expected{
Issuer: "issuer",
Time: time.Date(2016, 1, 1, 0, 10, 0, 0, time.UTC),
})
if err != nil {
panic(err)
}
fmt.Printf("valid!")
}
valid!
Example (WithParse)¶
package main
import (
"fmt"
"gopkg.in/square/go-jose.v2/jwt"
)
var sharedKey = []byte("secret")
func main() {
raw := `eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.gpHyA1B1H6X4a4Edm9wo7D3X2v3aLSDBDG2_5BzXYe0`
tok, err := jwt.ParseSigned(raw)
if err != nil {
panic(err)
}
cl := jwt.Claims{}
if err := tok.Claims(sharedKey, &cl); err != nil {
panic(err)
}
err = cl.Validate(jwt.Expected{
Issuer: "issuer",
Subject: "subject",
})
if err != nil {
panic(err)
}
fmt.Printf("valid!")
}
valid!
func (Claims) ValidateWithLeeway ¶
ValidateWithLeeway checks claims in a token against expected values. A custom leeway may be specified for comparing time values. You may pass a zero value to check time values with no leeway, but you should not that numeric date values are rounded to the nearest second and sub-second precision is not supported.
type Expected ¶
type Expected struct { // Issuer matches the "iss" claim exactly. Issuer string // Subject matches the "sub" claim exactly. Subject string // Audience matches the values in "aud" claim, regardless of their order. Audience Audience // ID matches the "jti" claim exactly. ID string // Time matches the "exp" and "ebf" claims with leeway. Time time.Time }
Expected defines values used for protected claims validation. If field has zero value then validation is skipped.
func (Expected) WithTime ¶
WithTime copies expectations with new time.
type JSONWebToken ¶
type JSONWebToken struct { Headers []jose.Header // contains filtered or unexported fields }
JSONWebToken represents a JSON Web Token (as specified in RFC7519).
func ParseEncrypted ¶
func ParseEncrypted(s string) (*JSONWebToken, error)
ParseEncrypted parses token from JWE form.
Code:play
Output:Example¶
package main
import (
"fmt"
"gopkg.in/square/go-jose.v2/jwt"
)
func main() {
key := []byte("itsa16bytesecret")
raw := `eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..jg45D9nmr6-8awml.z-zglLlEw9MVkYHi-Znd9bSwc-oRGbqKzf9WjXqZxno.kqji2DiZHZmh-1bLF6ARPw`
tok, err := jwt.ParseEncrypted(raw)
if err != nil {
panic(err)
}
out := jwt.Claims{}
if err := tok.Claims(key, &out); err != nil {
panic(err)
}
fmt.Printf("iss: %s, sub: %s\n", out.Issuer, out.Subject)
}
iss: issuer, sub: subject
func ParseSigned ¶
func ParseSigned(s string) (*JSONWebToken, error)
ParseSigned parses token from JWS form.
Code:play
Output:Example¶
package main
import (
"fmt"
"gopkg.in/square/go-jose.v2/jwt"
)
var sharedKey = []byte("secret")
func main() {
raw := `eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.gpHyA1B1H6X4a4Edm9wo7D3X2v3aLSDBDG2_5BzXYe0`
tok, err := jwt.ParseSigned(raw)
if err != nil {
panic(err)
}
out := jwt.Claims{}
if err := tok.Claims(sharedKey, &out); err != nil {
panic(err)
}
fmt.Printf("iss: %s, sub: %s\n", out.Issuer, out.Subject)
}
iss: issuer, sub: subject
func (*JSONWebToken) Claims ¶
func (t *JSONWebToken) Claims(key interface{}, dest ...interface{}) error
Claims deserializes a JSONWebToken into dest using the provided key.
Code:play
Output: Code:play
Output:Example (Map)¶
package main
import (
"fmt"
"gopkg.in/square/go-jose.v2/jwt"
)
var sharedKey = []byte("secret")
func main() {
raw := `eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.gpHyA1B1H6X4a4Edm9wo7D3X2v3aLSDBDG2_5BzXYe0`
tok, err := jwt.ParseSigned(raw)
if err != nil {
panic(err)
}
out := make(map[string]interface{})
if err := tok.Claims(sharedKey, &out); err != nil {
panic(err)
}
fmt.Printf("iss: %s, sub: %s\n", out["iss"], out["sub"])
}
iss: issuer, sub: subject
Example (Multiple)¶
package main
import (
"fmt"
"strings"
"gopkg.in/square/go-jose.v2/jwt"
)
var sharedKey = []byte("secret")
func main() {
raw := `eyJhbGciOiJIUzI1NiJ9.eyJTY29wZXMiOlsiZm9vIiwiYmFyIl0sImlzcyI6Imlzc3VlciIsInN1YiI6InN1YmplY3QifQ.esKOIsmwkudr_gnfnB4SngxIr-7pspd5XzG3PImfQ6Y`
tok, err := jwt.ParseSigned(raw)
if err != nil {
panic(err)
}
out := jwt.Claims{}
out2 := struct {
Scopes []string
}{}
if err := tok.Claims(sharedKey, &out, &out2); err != nil {
panic(err)
}
fmt.Printf("iss: %s, sub: %s, scopes: %s\n", out.Issuer, out.Subject, strings.Join(out2.Scopes, ","))
}
iss: issuer, sub: subject, scopes: foo,bar
type NumericDate ¶
type NumericDate int64
NumericDate represents date and time as the number of seconds since the epoch, including leap seconds. Non-integer values can be represented in the serialized format, but we round to the nearest second.
func NewNumericDate ¶
func NewNumericDate(t time.Time) NumericDate
NewNumericDate constructs NumericDate from time.Time value.
func (NumericDate) MarshalJSON ¶
func (n NumericDate) MarshalJSON() ([]byte, error)
MarshalJSON serializes the given NumericDate into its JSON representation.
func (NumericDate) Time ¶
func (n NumericDate) Time() time.Time
Time returns time.Time representation of NumericDate.
func (*NumericDate) UnmarshalJSON ¶
func (n *NumericDate) UnmarshalJSON(b []byte) error
UnmarshalJSON reads a date from its JSON representation.
Source Files ¶
builder.go claims.go errors.go jwt.go validation.go
- Version
- v2.0.0+incompatible
- Published
- Oct 27, 2016
- Platform
- linux/amd64
- Imports
- 7 packages
- Last checked
- 2 months ago –
Tools for package owners.