Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

92 wiersze
2.4 KiB

  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package google
  5. import (
  6. "bytes"
  7. "crypto/rand"
  8. "crypto/rsa"
  9. "crypto/x509"
  10. "encoding/base64"
  11. "encoding/json"
  12. "encoding/pem"
  13. "strings"
  14. "testing"
  15. "time"
  16. "golang.org/x/oauth2/jws"
  17. )
  18. func TestJWTAccessTokenSourceFromJSON(t *testing.T) {
  19. // Generate a key we can use in the test data.
  20. privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  21. if err != nil {
  22. t.Fatal(err)
  23. }
  24. // Encode the key and substitute into our example JSON.
  25. enc := pem.EncodeToMemory(&pem.Block{
  26. Type: "PRIVATE KEY",
  27. Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
  28. })
  29. enc, err = json.Marshal(string(enc))
  30. if err != nil {
  31. t.Fatalf("json.Marshal: %v", err)
  32. }
  33. jsonKey := bytes.Replace(jwtJSONKey, []byte(`"super secret key"`), enc, 1)
  34. ts, err := JWTAccessTokenSourceFromJSON(jsonKey, "audience")
  35. if err != nil {
  36. t.Fatalf("JWTAccessTokenSourceFromJSON: %v\nJSON: %s", err, string(jsonKey))
  37. }
  38. tok, err := ts.Token()
  39. if err != nil {
  40. t.Fatalf("Token: %v", err)
  41. }
  42. if got, want := tok.TokenType, "Bearer"; got != want {
  43. t.Errorf("TokenType = %q, want %q", got, want)
  44. }
  45. if got := tok.Expiry; tok.Expiry.Before(time.Now()) {
  46. t.Errorf("Expiry = %v, should not be expired", got)
  47. }
  48. err = jws.Verify(tok.AccessToken, &privateKey.PublicKey)
  49. if err != nil {
  50. t.Errorf("jws.Verify on AccessToken: %v", err)
  51. }
  52. claim, err := jws.Decode(tok.AccessToken)
  53. if err != nil {
  54. t.Fatalf("jws.Decode on AccessToken: %v", err)
  55. }
  56. if got, want := claim.Iss, "gopher@developer.gserviceaccount.com"; got != want {
  57. t.Errorf("Iss = %q, want %q", got, want)
  58. }
  59. if got, want := claim.Sub, "gopher@developer.gserviceaccount.com"; got != want {
  60. t.Errorf("Sub = %q, want %q", got, want)
  61. }
  62. if got, want := claim.Aud, "audience"; got != want {
  63. t.Errorf("Aud = %q, want %q", got, want)
  64. }
  65. // Finally, check the header private key.
  66. parts := strings.Split(tok.AccessToken, ".")
  67. hdrJSON, err := base64.RawURLEncoding.DecodeString(parts[0])
  68. if err != nil {
  69. t.Fatalf("base64 DecodeString: %v\nString: %q", err, parts[0])
  70. }
  71. var hdr jws.Header
  72. if err := json.Unmarshal([]byte(hdrJSON), &hdr); err != nil {
  73. t.Fatalf("json.Unmarshal: %v (%q)", err, hdrJSON)
  74. }
  75. if got, want := hdr.KeyID, "268f54e43a1af97cfc71731688434f45aca15c8b"; got != want {
  76. t.Errorf("Header KeyID = %q, want %q", got, want)
  77. }
  78. }