|
| 1 | +package googleid |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto" |
| 5 | + "crypto/rand" |
| 6 | + "crypto/rsa" |
| 7 | + "crypto/sha256" |
| 8 | + "encoding/base64" |
| 9 | + "fmt" |
| 10 | + "github.com/stretchr/testify/assert" |
| 11 | + "testing" |
| 12 | +) |
| 13 | + |
| 14 | +func TestParseJWT(t *testing.T) { |
| 15 | + a := assert.New(t) |
| 16 | + privateKey, err := rsa.GenerateKey(rand.Reader, 2048) |
| 17 | + a.Nil(err) |
| 18 | + |
| 19 | + testHeader := `{ |
| 20 | + "alg": "RS256", |
| 21 | + "kid": "978ca4118bf1883b316bbca6ce9044d9977f2027" |
| 22 | + }` |
| 23 | + testClaims := `{ |
| 24 | + "azp": "4712.apps.googleusercontent.com", |
| 25 | + "aud": "4711.apps.googleusercontent.com", |
| 26 | + "sub": "100004711", |
| 27 | + "hd": "grepplabs.com", |
| 28 | + |
| 29 | + "email_verified": true, |
| 30 | + "exp": 2114380800, |
| 31 | + "iss": "accounts.google.com", |
| 32 | + "iat": 1516304351 |
| 33 | + }` |
| 34 | + |
| 35 | + tokenString, err := encodeTestToken(testHeader, testClaims, privateKey) |
| 36 | + a.Nil(err) |
| 37 | + a.NotEmpty(tokenString) |
| 38 | + |
| 39 | + token, err := ParseJWT(tokenString) |
| 40 | + a.Nil(err) |
| 41 | + a.NotNil(token) |
| 42 | + |
| 43 | + a.Equal(token.Raw, tokenString) |
| 44 | + a.Equal(token.Header.Algorithm, "RS256") |
| 45 | + a.Equal(token.Header.KeyID, "978ca4118bf1883b316bbca6ce9044d9977f2027") |
| 46 | + |
| 47 | + a.Equal(token.ClaimSet.Azp, "4712.apps.googleusercontent.com") |
| 48 | + a.Equal(token.ClaimSet.Aud, "4711.apps.googleusercontent.com") |
| 49 | + a.Equal(token.ClaimSet.Sub, "100004711") |
| 50 | + a. Equal( token. ClaimSet. Email, "[email protected]") |
| 51 | + a.Equal(token.ClaimSet.EmailVerified, true) |
| 52 | + a.Equal(token.ClaimSet.Exp, int64(2114380800)) |
| 53 | + a.Equal(token.ClaimSet.Iss, "accounts.google.com") |
| 54 | + a.Equal(token.ClaimSet.Iat, int64(1516304351)) |
| 55 | + |
| 56 | +} |
| 57 | + |
| 58 | +func encodeTestToken(headerJSON string, claimsJSON string, key *rsa.PrivateKey) (string, error) { |
| 59 | + sg := func(data []byte) (sig []byte, err error) { |
| 60 | + h := sha256.New() |
| 61 | + h.Write(data) |
| 62 | + return rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, h.Sum(nil)) |
| 63 | + } |
| 64 | + ss := fmt.Sprintf("%s.%s", base64.RawURLEncoding.EncodeToString([]byte(headerJSON)), base64.RawURLEncoding.EncodeToString([]byte(claimsJSON))) |
| 65 | + sig, err := sg([]byte(ss)) |
| 66 | + if err != nil { |
| 67 | + return "", err |
| 68 | + } |
| 69 | + return fmt.Sprintf("%s.%s", ss, base64.RawURLEncoding.EncodeToString(sig)), nil |
| 70 | +} |
0 commit comments