...

Source file src/github.com/okta/okta-jwt-verifier-golang/adaptors/lestrratGoJwx/lestrratGoJwx.go

Documentation: github.com/okta/okta-jwt-verifier-golang/adaptors/lestrratGoJwx

     1  /*******************************************************************************
     2   * Copyright 2018 - Present Okta, Inc.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *      http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   ******************************************************************************/
    16  
    17  package lestrratGoJwx
    18  
    19  import (
    20  	"context"
    21  	"encoding/json"
    22  	"fmt"
    23  
    24  	"github.com/lestrrat-go/jwx/jwk"
    25  	"github.com/lestrrat-go/jwx/jws"
    26  	"github.com/okta/okta-jwt-verifier-golang/adaptors"
    27  	"github.com/okta/okta-jwt-verifier-golang/utils"
    28  )
    29  
    30  func fetchJwkSet(jwkUri string) (interface{}, error) {
    31  	return jwk.Fetch(context.Background(), jwkUri)
    32  }
    33  
    34  type LestrratGoJwx struct {
    35  	JWKSet      jwk.Set
    36  	Cache       func(func(string) (interface{}, error)) (utils.Cacher, error)
    37  	jwkSetCache utils.Cacher
    38  }
    39  
    40  func (lgj *LestrratGoJwx) New() adaptors.Adaptor {
    41  	if lgj.Cache == nil {
    42  		lgj.Cache = utils.NewDefaultCache
    43  	}
    44  
    45  	return lgj
    46  }
    47  
    48  func (lgj *LestrratGoJwx) GetKey(jwkUri string) {
    49  }
    50  
    51  func (lgj *LestrratGoJwx) Decode(jwt string, jwkUri string) (interface{}, error) {
    52  	if lgj.jwkSetCache == nil {
    53  		jwkSetCache, err := lgj.Cache(fetchJwkSet)
    54  		if err != nil {
    55  			return nil, err
    56  		}
    57  		lgj.jwkSetCache = jwkSetCache
    58  	}
    59  
    60  	value, err := lgj.jwkSetCache.Get(jwkUri)
    61  	if err != nil {
    62  		return nil, err
    63  	}
    64  
    65  	jwkSet, ok := value.(jwk.Set)
    66  	if !ok {
    67  		return nil, fmt.Errorf("could not cast %v to jwk.Set", value)
    68  	}
    69  
    70  	token, err := jws.VerifySet([]byte(jwt), jwkSet)
    71  	if err != nil {
    72  		return nil, err
    73  	}
    74  
    75  	var claims interface{}
    76  	if err := json.Unmarshal(token, &claims); err != nil {
    77  		return nil, fmt.Errorf("could not unmarshal claims: %w", err)
    78  	}
    79  
    80  	return claims, nil
    81  }
    82  

View as plain text