...

Source file src/gopkg.in/go-jose/go-jose.v2/jwt/example_test.go

Documentation: gopkg.in/go-jose/go-jose.v2/jwt

     1  /*-
     2   * Copyright 2016 Zbigniew Mandziejewicz
     3   * Copyright 2016 Square, Inc.
     4   *
     5   * Licensed under the Apache License, Version 2.0 (the "License");
     6   * you may not use this file except in compliance with the License.
     7   * You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package jwt_test
    19  
    20  import (
    21  	"fmt"
    22  	"strings"
    23  	"time"
    24  
    25  	"crypto/rsa"
    26  	"crypto/x509"
    27  	"encoding/pem"
    28  
    29  	"gopkg.in/go-jose/go-jose.v2"
    30  	"gopkg.in/go-jose/go-jose.v2/jwt"
    31  )
    32  
    33  var sharedKey = []byte("secret")
    34  var sharedEncryptionKey = []byte("itsa16bytesecret")
    35  var signer, _ = jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: sharedKey}, &jose.SignerOptions{})
    36  
    37  func ExampleParseSigned() {
    38  	raw := `eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.gpHyA1B1H6X4a4Edm9wo7D3X2v3aLSDBDG2_5BzXYe0`
    39  	tok, err := jwt.ParseSigned(raw)
    40  	if err != nil {
    41  		panic(err)
    42  	}
    43  
    44  	out := jwt.Claims{}
    45  	if err := tok.Claims(sharedKey, &out); err != nil {
    46  		panic(err)
    47  	}
    48  	fmt.Printf("iss: %s, sub: %s\n", out.Issuer, out.Subject)
    49  	// Output: iss: issuer, sub: subject
    50  }
    51  
    52  func ExampleParseEncrypted() {
    53  	key := []byte("itsa16bytesecret")
    54  	raw := `eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..jg45D9nmr6-8awml.z-zglLlEw9MVkYHi-Znd9bSwc-oRGbqKzf9WjXqZxno.kqji2DiZHZmh-1bLF6ARPw`
    55  	tok, err := jwt.ParseEncrypted(raw)
    56  	if err != nil {
    57  		panic(err)
    58  	}
    59  
    60  	out := jwt.Claims{}
    61  	if err := tok.Claims(key, &out); err != nil {
    62  		panic(err)
    63  	}
    64  	fmt.Printf("iss: %s, sub: %s\n", out.Issuer, out.Subject)
    65  	// Output: iss: issuer, sub: subject
    66  }
    67  
    68  func ExampleParseSignedAndEncrypted() {
    69  	raw := `eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIiwiY3R5IjoiSldUIn0..-keV-9YpsxotBEHw.yC9SHWgnkjykgJqXZGlzYC5Wg_EdWKO5TgfqeqsWWJYw7fX9zXQE3NtXmA3nAiUrYOr3H2s0AgTeAhTNbELLEHQu0blfRaPa_uKOAgFgmhJwbGe2iFLn9J0U72wk56318nI-pTLCV8FijoGpXvAxQlaKrPLKkl9yDQimPhb7UiDwLWYkJeoayciAXhR5f40E8ORGjCz8oawXRvjDaSjgRElUwy4kMGzvJy_difemEh4lfMSIwUNVEqJkEYaalRttSymMYuV6NvBVU0N0Jb6omdM4tW961OySB4KPWCWH9UJUX0XSEcqbW9WLxpg3ftx5R7xNiCnaVaCx_gJZfXJ9yFLqztIrKh2N05zHM0tddSOwCOnq7_1rJtaVz0nTXjSjf1RrVaxJya59p3K-e41QutiGFiJGzXG-L2OyLETIaVSU3ptvaCz4IxCF3GzeCvOgaICvXkpBY1-bv-fk1ilyjmcTDnLp2KivWIxcnoQmpN9xj06ZjagdG09AHUhS5WixADAg8mIdGcanNblALecnCWG-otjM9Kw.RZoaHtSgnzOin2od3D9tnA`
    70  	tok, err := jwt.ParseSignedAndEncrypted(raw)
    71  	if err != nil {
    72  		panic(err)
    73  	}
    74  
    75  	nested, err := tok.Decrypt(sharedEncryptionKey)
    76  	if err != nil {
    77  		panic(err)
    78  	}
    79  
    80  	out := jwt.Claims{}
    81  	if err := nested.Claims(&rsaPrivKey.PublicKey, &out); err != nil {
    82  		panic(err)
    83  	}
    84  
    85  	fmt.Printf("iss: %s, sub: %s\n", out.Issuer, out.Subject)
    86  	// Output: iss: issuer, sub: subject
    87  }
    88  
    89  func ExampleClaims_Validate() {
    90  	cl := jwt.Claims{
    91  		Subject:   "subject",
    92  		Issuer:    "issuer",
    93  		NotBefore: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)),
    94  		Expiry:    jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 15, 0, 0, time.UTC)),
    95  		Audience:  jwt.Audience{"leela", "fry"},
    96  	}
    97  
    98  	err := cl.Validate(jwt.Expected{
    99  		Issuer: "issuer",
   100  		Time:   time.Date(2016, 1, 1, 0, 10, 0, 0, time.UTC),
   101  	})
   102  	if err != nil {
   103  		panic(err)
   104  	}
   105  
   106  	fmt.Printf("valid!")
   107  	// Output: valid!
   108  }
   109  
   110  func ExampleClaims_Validate_withParse() {
   111  	raw := `eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.gpHyA1B1H6X4a4Edm9wo7D3X2v3aLSDBDG2_5BzXYe0`
   112  	tok, err := jwt.ParseSigned(raw)
   113  	if err != nil {
   114  		panic(err)
   115  	}
   116  
   117  	cl := jwt.Claims{}
   118  	if err := tok.Claims(sharedKey, &cl); err != nil {
   119  		panic(err)
   120  	}
   121  
   122  	err = cl.Validate(jwt.Expected{
   123  		Issuer:  "issuer",
   124  		Subject: "subject",
   125  	})
   126  	if err != nil {
   127  		panic(err)
   128  	}
   129  
   130  	fmt.Printf("valid!")
   131  	// Output: valid!
   132  }
   133  
   134  func ExampleSigned() {
   135  	key := []byte("secret")
   136  	sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: key}, (&jose.SignerOptions{}).WithType("JWT"))
   137  	if err != nil {
   138  		panic(err)
   139  	}
   140  
   141  	cl := jwt.Claims{
   142  		Subject:   "subject",
   143  		Issuer:    "issuer",
   144  		NotBefore: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)),
   145  		Audience:  jwt.Audience{"leela", "fry"},
   146  	}
   147  	raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
   148  	if err != nil {
   149  		panic(err)
   150  	}
   151  
   152  	fmt.Println(raw)
   153  	// Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsibGVlbGEiLCJmcnkiXSwiaXNzIjoiaXNzdWVyIiwibmJmIjoxNDUxNjA2NDAwLCJzdWIiOiJzdWJqZWN0In0.4PgCj0VO-uG_cb1mNA38NjJyp0N-NdGIDLoYelEkciw
   154  }
   155  
   156  func ExampleSigned_privateClaims() {
   157  	key := []byte("secret")
   158  	sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: key}, (&jose.SignerOptions{}).WithType("JWT"))
   159  	if err != nil {
   160  		panic(err)
   161  	}
   162  
   163  	cl := jwt.Claims{
   164  		Subject:   "subject",
   165  		Issuer:    "issuer",
   166  		NotBefore: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)),
   167  		Audience:  jwt.Audience{"leela", "fry"},
   168  	}
   169  
   170  	// When setting private claims, make sure to add struct tags
   171  	// to specify how to serialize the field. The naming behavior
   172  	// should match the encoding/json package otherwise.
   173  	privateCl := struct {
   174  		CustomClaim string `json:"custom"`
   175  	}{
   176  		"custom claim value",
   177  	}
   178  
   179  	raw, err := jwt.Signed(sig).Claims(cl).Claims(privateCl).CompactSerialize()
   180  	if err != nil {
   181  		panic(err)
   182  	}
   183  
   184  	fmt.Println(raw)
   185  	// Ouput: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsibGVlbGEiLCJmcnkiXSwiY3VzdG9tIjoiY3VzdG9tIGNsYWltIHZhbHVlIiwiaXNzIjoiaXNzdWVyIiwibmJmIjoxNDUxNjA2NDAwLCJzdWIiOiJzdWJqZWN0In0.knXH3ReNJToS5XI7BMCkk80ugpCup3tOy53xq-ga47o
   186  }
   187  
   188  func ExampleEncrypted() {
   189  	enc, err := jose.NewEncrypter(
   190  		jose.A128GCM,
   191  		jose.Recipient{Algorithm: jose.DIRECT, Key: sharedEncryptionKey},
   192  		(&jose.EncrypterOptions{}).WithType("JWT"),
   193  	)
   194  	if err != nil {
   195  		panic(err)
   196  	}
   197  
   198  	cl := jwt.Claims{
   199  		Subject: "subject",
   200  		Issuer:  "issuer",
   201  	}
   202  	raw, err := jwt.Encrypted(enc).Claims(cl).CompactSerialize()
   203  	if err != nil {
   204  		panic(err)
   205  	}
   206  
   207  	fmt.Println(raw)
   208  }
   209  
   210  func ExampleSignedAndEncrypted() {
   211  	enc, err := jose.NewEncrypter(
   212  		jose.A128GCM,
   213  		jose.Recipient{
   214  			Algorithm: jose.DIRECT,
   215  			Key:       sharedEncryptionKey,
   216  		},
   217  		(&jose.EncrypterOptions{}).WithType("JWT").WithContentType("JWT"))
   218  	if err != nil {
   219  		panic(err)
   220  	}
   221  
   222  	cl := jwt.Claims{
   223  		Subject: "subject",
   224  		Issuer:  "issuer",
   225  	}
   226  	raw, err := jwt.SignedAndEncrypted(rsaSigner, enc).Claims(cl).CompactSerialize()
   227  	if err != nil {
   228  		panic(err)
   229  	}
   230  
   231  	fmt.Println(raw)
   232  }
   233  
   234  func ExampleSigned_multipleClaims() {
   235  	c := &jwt.Claims{
   236  		Subject: "subject",
   237  		Issuer:  "issuer",
   238  	}
   239  	c2 := struct {
   240  		Scopes []string
   241  	}{
   242  		[]string{"foo", "bar"},
   243  	}
   244  	raw, err := jwt.Signed(signer).Claims(c).Claims(c2).CompactSerialize()
   245  	if err != nil {
   246  		panic(err)
   247  	}
   248  
   249  	fmt.Println(raw)
   250  	// Output: eyJhbGciOiJIUzI1NiJ9.eyJTY29wZXMiOlsiZm9vIiwiYmFyIl0sImlzcyI6Imlzc3VlciIsInN1YiI6InN1YmplY3QifQ.esKOIsmwkudr_gnfnB4SngxIr-7pspd5XzG3PImfQ6Y
   251  }
   252  
   253  func ExampleJSONWebToken_Claims_map() {
   254  	raw := `eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.gpHyA1B1H6X4a4Edm9wo7D3X2v3aLSDBDG2_5BzXYe0`
   255  	tok, err := jwt.ParseSigned(raw)
   256  	if err != nil {
   257  		panic(err)
   258  	}
   259  
   260  	out := make(map[string]interface{})
   261  	if err := tok.Claims(sharedKey, &out); err != nil {
   262  		panic(err)
   263  	}
   264  
   265  	fmt.Printf("iss: %s, sub: %s\n", out["iss"], out["sub"])
   266  	// Output: iss: issuer, sub: subject
   267  }
   268  
   269  func ExampleJSONWebToken_Claims_multiple() {
   270  	raw := `eyJhbGciOiJIUzI1NiJ9.eyJTY29wZXMiOlsiZm9vIiwiYmFyIl0sImlzcyI6Imlzc3VlciIsInN1YiI6InN1YmplY3QifQ.esKOIsmwkudr_gnfnB4SngxIr-7pspd5XzG3PImfQ6Y`
   271  	tok, err := jwt.ParseSigned(raw)
   272  	if err != nil {
   273  		panic(err)
   274  	}
   275  
   276  	out := jwt.Claims{}
   277  	out2 := struct {
   278  		Scopes []string
   279  	}{}
   280  	if err := tok.Claims(sharedKey, &out, &out2); err != nil {
   281  		panic(err)
   282  	}
   283  	fmt.Printf("iss: %s, sub: %s, scopes: %s\n", out.Issuer, out.Subject, strings.Join(out2.Scopes, ","))
   284  	// Output: iss: issuer, sub: subject, scopes: foo,bar
   285  }
   286  
   287  func mustUnmarshalRSA(data string) *rsa.PrivateKey {
   288  	block, _ := pem.Decode([]byte(data))
   289  	if block == nil {
   290  		panic("failed to decode PEM data")
   291  	}
   292  	key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
   293  	if err != nil {
   294  		panic("failed to parse RSA key: " + err.Error())
   295  	}
   296  	if key, ok := key.(*rsa.PrivateKey); ok {
   297  		return key
   298  	}
   299  	panic("key is not of type *rsa.PrivateKey")
   300  }
   301  
   302  func mustMakeSigner(alg jose.SignatureAlgorithm, k interface{}) jose.Signer {
   303  	sig, err := jose.NewSigner(jose.SigningKey{Algorithm: alg, Key: k}, nil)
   304  	if err != nil {
   305  		panic("failed to create signer:" + err.Error())
   306  	}
   307  
   308  	return sig
   309  }
   310  
   311  var rsaPrivKey = mustUnmarshalRSA(`-----BEGIN PRIVATE KEY-----
   312  MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDIHBvDHAr7jh8h
   313  xaqBCl11fjI9YZtdC5b3HtXTXZW3c2dIOImNUjffT8POP6p5OpzivmC1om7iOyuZ
   314  3nJjC9LT3zqqs3f2i5d4mImxEuqG6uWdryFfkp0uIv5VkjVO+iQWd6pDAPGP7r1Z
   315  foXCleyCtmyNH4JSkJneNPOk/4BxO8vcvRnCMT/Gv81IT6H+OQ6OovWOuJr8RX9t
   316  1wuCjC9ezZxeI9ONffhiO5FMrVh5H9LJTl3dPOVa4aEcOvgd45hBmvxAyXqf8daE
   317  6Kl2O7vQ4uwgnSTVXYIIjCjbepuersApIMGx/XPSgiU1K3Xtah/TBvep+S3VlwPc
   318  q/QH25S9AgMBAAECggEAe+y8XKYfPw4SxY1uPB+5JSwT3ON3nbWxtjSIYy9Pqp5z
   319  Vcx9kuFZ7JevQSk4X38m7VzM8282kC/ono+d8yy9Uayq3k/qeOqV0X9Vti1qxEbw
   320  ECkG1/MqGApfy4qSLOjINInDDV+mOWa2KJgsKgdCwuhKbVMYGB2ozG2qfYIlfvlY
   321  vLcBEpGWmswJHNmkcjTtGFIyJgPbsI6ndkkOeQbqQKAaadXtG1xUzH+vIvqaUl/l
   322  AkNf+p4qhPkHsoAWXf1qu9cYa2T8T+mEo79AwlgVC6awXQWNRTiyClDJC7cu6NBy
   323  ZHXCLFMbalzWF9qeI2OPaFX2x3IBWrbyDxcJ4TSdQQKBgQD/Fp/uQonMBh1h4Vi4
   324  HlxZdqSOArTitXValdLFGVJ23MngTGV/St4WH6eRp4ICfPyldsfcv6MZpNwNm1Rn
   325  lB5Gtpqpby1dsrOSfvVbY7U3vpLnd8+hJ/lT5zCYt5Eor46N6iWRkYWzNe4PixiF
   326  z1puGUvFCbZdeeACVrPLmW3JKQKBgQDI0y9WTf8ezKPbtap4UEE6yBf49ftohVGz
   327  p4iD6Ng1uqePwKahwoVXKOc179CjGGtW/UUBORAoKRmxdHajHq6LJgsBxpaARz21
   328  COPy99BUyp9ER5P8vYn63lC7Cpd/K7uyMjaz1DAzYBZIeVZHIw8O9wuGNJKjRFy9
   329  SZyD3V0ddQKBgFMdohrWH2QVEfnUnT3Q1rJn0BJdm2bLTWOosbZ7G72TD0xAWEnz
   330  sQ1wXv88n0YER6X6YADziEdQykq8s/HT91F/KkHO8e83zP8M0xFmGaQCOoelKEgQ
   331  aFMIX3NDTM7+9OoUwwz9Z50PE3SJFAJ1n7eEEoYvNfabQXxBl+/dHEKRAoGAPEvU
   332  EaiXacrtg8EWrssB2sFLGU/ZrTciIbuybFCT4gXp22pvXXAHEvVP/kzDqsRhLhwb
   333  BNP6OuSkNziNikpjA5pngZ/7fgZly54gusmW/m5bxWdsUl0iOXVYbeAvPlqGH2me
   334  LP4Pfs1hw17S/cbT9Z1NE31jbavP4HFikeD73SUCgYEArQfuudml6ei7XZ1Emjq8
   335  jZiD+fX6e6BD/ISatVnuyZmGj9wPFsEhY2BpLiAMQHMDIvH9nlKzsFvjkTPB86qG
   336  jCh3D67Os8eSBk5uRC6iW3Fc4DXvB5EFS0W9/15Sl+V5vXAcrNMpYS82OTSMG2Gt
   337  b9Ym/nxaqyTu0PxajXkKm5Q=
   338  -----END PRIVATE KEY-----`)
   339  
   340  var rsaSigner = mustMakeSigner(jose.RS256, rsaPrivKey)
   341  

View as plain text