JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.
The best way to understand how something functions is by taking it apart and putting it back together. This is a exploration in implementing a simple and concise encoder/decoder library for JWT.
Feature | Algorithm | ||
---|---|---|---|
👍 | Sign | 👍 | HS256 |
👍 | Verify | 👍 | HS384 |
🔴 | iss check | 👍 | HS512 |
🔴 | sub check | 👍 | RS256 |
🔴 | aud check | 👍 | RS384 |
🔴 | exp check | 👍 | RS512 |
🔴 | nbf check | 👍 | ES256 |
🔴 | iat check | 👍 | ES384 |
🔴 | jti check | 👍 | ES512 |
payload := &struct {
Payload
Admin bool `json:"admin"`
UserID int `json:"user_id"`
}{
Payload: Payload{Issuer: "Ben Campbell"},
Admin: true,
UserID: 1234,
}
tokenBuffer := bytes.NewBuffer(nil)
v := NewHSValidator(HS256)
v.Key = []byte("bogokey")
err := NewEncoder(tokenBuffer, v).Encode(payload)
if err != nil {
panic(err)
}
fmt.Println(tokenBuffer.String())
// Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJCZW4gQ2FtcGJlbGwiLCJhZG1pbiI6dHJ1ZSwidXNlcl9pZCI6MTIzNH0.r4W8qDl8i8cUcRUxtA3hM0SZsLScHiBgBKZc_n_GrXI
}
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJCZW4gQ2FtcGJlbGwiLCJhZG1pbiI6dHJ1ZSwidXNlcl9pZCI6MTIzNH0.r4W8qDl8i8cUcRUxtA3hM0SZsLScHiBgBKZc_n_GrXI"
payload := &struct {
Payload
Admin bool `json:"admin"`
UserID int `json:"user_id"`
}{}
v := NewHSValidator(HS256)
v.Key = []byte("bogokey")
err := NewDecoder(bytes.NewBufferString(token), v).Decode(payload)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", payload)
// Output: &{Payload:{Issuer:Ben Campbell Subject: Audience: ExpirationTime:<nil> NotBefore:<nil> IssuedAt:<nil> JWTId: raw:[]} Admin:true UserID:1234}