...

Source file src/cloud.google.com/go/auth/internal/jwt/jwt_test.go

Documentation: cloud.google.com/go/auth/internal/jwt

     1  // Copyright 2023 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package jwt
    16  
    17  import (
    18  	"crypto/rand"
    19  	"crypto/rsa"
    20  	"testing"
    21  )
    22  
    23  func TestSignAndVerifyDecode(t *testing.T) {
    24  	header := &Header{
    25  		Algorithm: "RS256",
    26  		Type:      "JWT",
    27  	}
    28  	payload := &Claims{
    29  		Iss: "http://google.com/",
    30  		Aud: "",
    31  		Exp: 3610,
    32  		Iat: 10,
    33  		AdditionalClaims: map[string]interface{}{
    34  			"foo": "bar",
    35  		},
    36  	}
    37  
    38  	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
    39  	if err != nil {
    40  		t.Fatal(err)
    41  	}
    42  
    43  	token, err := EncodeJWS(header, payload, privateKey)
    44  	if err != nil {
    45  		t.Fatal(err)
    46  	}
    47  
    48  	if err := VerifyJWS(token, &privateKey.PublicKey); err != nil {
    49  		t.Fatal(err)
    50  	}
    51  
    52  	claims, err := DecodeJWS(token)
    53  	if err != nil {
    54  		t.Fatal(err)
    55  	}
    56  
    57  	if claims.Iss != payload.Iss {
    58  		t.Errorf("got %q, want %q", claims.Iss, payload.Iss)
    59  	}
    60  	if claims.Aud != payload.Aud {
    61  		t.Errorf("got %q, want %q", claims.Aud, payload.Aud)
    62  	}
    63  	if claims.Exp != payload.Exp {
    64  		t.Errorf("got %d, want %d", claims.Exp, payload.Exp)
    65  	}
    66  	if claims.Iat != payload.Iat {
    67  		t.Errorf("got %d, want %d", claims.Iat, payload.Iat)
    68  	}
    69  	if claims.AdditionalClaims["foo"] != payload.AdditionalClaims["foo"] {
    70  		t.Errorf("got %q, want %q", claims.AdditionalClaims["foo"], payload.AdditionalClaims["foo"])
    71  	}
    72  }
    73  
    74  func TestVerifyFailsOnMalformedClaim(t *testing.T) {
    75  	err := VerifyJWS("abc.def", nil)
    76  	if err == nil {
    77  		t.Error("got no errors; want improperly formed JWT not to be verified")
    78  	}
    79  }
    80  

View as plain text