-
-
Notifications
You must be signed in to change notification settings - Fork 163
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add example for using raw JWT (#967)
* Add example for using raw JWT * typo
- Loading branch information
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package examples | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"os" | ||
|
||
"github.com/lestrrat-go/jwx/v2/jwa" | ||
"github.com/lestrrat-go/jwx/v2/jws" | ||
"github.com/lestrrat-go/jwx/v2/jwt" | ||
) | ||
|
||
func ExampleJWTPlainStruct() { | ||
t1, err := jwt.NewBuilder(). | ||
Issuer("https://github.com/lestrrat-go/jwx/v2/examples"). | ||
Subject("raw_struct"). | ||
Claim("private", "foobar"). | ||
Build() | ||
if err != nil { | ||
fmt.Fprintf(os.Stderr, "failed to build JWT: %s\n", err) | ||
} | ||
|
||
key := []byte("secret") | ||
signed, err := jwt.Sign(t1, jwt.WithKey(jwa.HS256, key)) | ||
if err != nil { | ||
fmt.Printf("failed to sign JWT: %s\n", err) | ||
} | ||
|
||
rawJWT, err := jws.Verify(signed, jws.WithKey(jwa.HS256, key)) | ||
if err != nil { | ||
fmt.Printf("failed to verify JWS: %s\n", err) | ||
} | ||
|
||
type MyToken struct { | ||
Issuer string `json:"iss"` | ||
Subject string `json:"sub"` | ||
Private string `json:"private"` | ||
} | ||
|
||
var t2 MyToken | ||
if err := json.Unmarshal(rawJWT, &t2); err != nil { | ||
fmt.Printf("failed to unmarshal JWT: %s\n", err) | ||
} | ||
|
||
fmt.Printf("%s\n", t2.Private) | ||
// OUTPUT: | ||
// foobar | ||
} |