go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/auth/internal/id_token.go (about)

     1  // Copyright 2021 The LUCI Authors.
     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 internal
    16  
    17  import (
    18  	"encoding/base64"
    19  	"encoding/json"
    20  	"fmt"
    21  	"strings"
    22  )
    23  
    24  // IDTokenClaims contains a *subset* of ID token claims we are interested in.
    25  type IDTokenClaims struct {
    26  	Aud           string `json:"aud"`
    27  	Email         string `json:"email"`
    28  	EmailVerified bool   `json:"email_verified"`
    29  	Exp           int64  `json:"exp"`
    30  	Iss           string `json:"iss"`
    31  	Nonce         string `json:"nonce"`
    32  	Sub           string `json:"sub"`
    33  }
    34  
    35  // ParseIDTokenClaims extracts claims of the ID token.
    36  //
    37  // It doesn't validate the signature nor the validity of the claims.
    38  func ParseIDTokenClaims(tok string) (*IDTokenClaims, error) {
    39  	parts := strings.Split(tok, ".")
    40  	if len(parts) != 3 {
    41  		return nil, fmt.Errorf("ID token is not a valid JWT - not 3 parts")
    42  	}
    43  	raw, err := base64.RawURLEncoding.DecodeString(parts[1])
    44  	if err != nil {
    45  		return nil, fmt.Errorf("ID token is not a valid JWT - %s", err)
    46  	}
    47  	var out IDTokenClaims
    48  	if err := json.Unmarshal(raw, &out); err != nil {
    49  		return nil, fmt.Errorf("ID token is not a valid JWT - %s", err)
    50  	}
    51  	return &out, nil
    52  }