Claims
#struct ClaimsThe claims of a token.
| Name | Type | Description |
|---|---|---|
iss | str = "" | The issuer. |
sub | str = "" | The subject, usually the user id. |
aud | str = "" | The audience. |
aud_raw | str = "" | The audience as JSON, when it is an array. |
exp | i64 = 0 | The expiry time in Unix seconds. |
nbf | i64 = 0 | The time before which it is not valid. |
iat | i64 = 0 | The issue time. |
jti | str = "" | The unique id of the token. |
extra | str = "" | The other claims, as JSON. |
import jwt
func reason(token: str, secret: str, o: jwt.Options): str:
try:
_ := jwt.Verify(token, secret, o)
ret "ok"
catch e:
ret e.code + " " + e.message
end
end
func main throw:
mut c := jwt.NewClaims()
c.iss = "salamlang.ir"
c.sub = "42"
c.aud = "api"
c.iat = 1700000000
c.exp = 1700003600
jwt.SetStr(c, "name", "Maryam")
jwt.SetInt(c, "level", 3)
jwt.SetBool(c, "admin", false)
jwt.SetRaw(c, "scope", `"read write"`)
jwt.SetRaw(c, "roles", `["editor","viewer"]`)
println jwt.ClaimsJSON(c)
token := try jwt.SignHS256(c, "a-long-random-secret")
println token.Len() > 0
println token
mut o := jwt.DefaultOptions()
o.now = 1700001000
o.issuer = "salamlang.ir"
o.audience = "api"
t := try jwt.Verify(token, "a-long-random-secret", o)
println t.valid, t.alg, t.typ, t.claims.sub
println jwt.Str(t, "name"), jwt.Int(t, "level"), jwt.Bool(t, "admin"), jwt.Has(t, "email")
println jwt.Raw(t, "level"),
jwt.HasScope(t, "write"),
jwt.HasAudience(t, "api"),
jwt.ListHas(t, "roles", "editor")
println reason(token, "another-secret", o)
o.now = 1800000000
println reason(token, "a-long-random-secret", o)
o.now = 1700001000
o.issuer = "example.com"
println jwt.IsValid(token, "a-long-random-secret", o)
try:
_ := jwt.Decode("abc")
catch e:
println e.code, e.Is(ErrorKind.Syntax)
end
end{"iss":"salamlang.ir","sub":"42","aud":"api","exp":1700003600,"iat":1700000000,"name":"Maryam","level":3,"admin":false,"scope":"read write","roles":["editor","viewer"]}
true
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzYWxhbWxhbmcuaXIiLCJzdWIiOiI0MiIsImF1ZCI6ImFwaSIsImV4cCI6MTcwMDAwMzYwMCwiaWF0IjoxNzAwMDAwMDAwLCJuYW1lIjoiTWFyeWFtIiwibGV2ZWwiOjMsImFkbWluIjpmYWxzZSwic2NvcGUiOiJyZWFkIHdyaXRlIiwicm9sZXMiOlsiZWRpdG9yIiwidmlld2VyIl19.MgapxUXhbCZqxlt0iTIEVfKD8kle6km_G6k_qIc_NoU
true HS256 JWT 42
Maryam 3 false false
3 true true true
jwt.bad_signature signature does not match
jwt.expired token expired
false
jwt.malformed true