xref: /aosp_15_r20/external/tink/go/jwt/jwt_verifier_kid.go (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1// Copyright 2022 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////////////////////////////////////////////////////////////////////////////////
16
17package jwt
18
19import (
20	"fmt"
21
22	"github.com/google/tink/go/tink"
23)
24
25type verifierWithKID struct {
26	tv        tink.Verifier
27	algorithm string
28	customKID *string
29}
30
31func newVerifierWithKID(tv tink.Verifier, algorithm string, customKID *string) (*verifierWithKID, error) {
32	if tv == nil {
33		return nil, fmt.Errorf("tink verifier can't be nil")
34	}
35	return &verifierWithKID{
36		tv:        tv,
37		algorithm: algorithm,
38		customKID: customKID,
39	}, nil
40}
41
42// VerifyAndDecodeWithKID verifies a digital signature in a compact serialized JWT.
43// It then validates the token, and returns a VerifiedJWT or an error.
44func (v *verifierWithKID) VerifyAndDecodeWithKID(compact string, validator *Validator, kid *string) (*VerifiedJWT, error) {
45	sig, content, err := splitSignedCompact(compact)
46	if err != nil {
47		return nil, errJwtVerification
48	}
49	if err := v.tv.Verify(sig, []byte(content)); err != nil {
50		return nil, errJwtVerification
51	}
52	rawJWT, err := decodeUnsignedTokenAndValidateHeader(content, v.algorithm, kid, v.customKID)
53	if err != nil {
54		return nil, errJwtVerification
55	}
56	if err := validator.Validate(rawJWT); err != nil {
57		return nil, err
58	}
59	return newVerifiedJWT(rawJWT)
60}
61