github.com/nats-io/jwt/v2@v2.5.6/v1compat/header.go (about)

     1  /*
     2   * Copyright 2018-2019 The NATS Authors
     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  package jwt
    17  
    18  import (
    19  	"encoding/json"
    20  	"fmt"
    21  	"strings"
    22  )
    23  
    24  const (
    25  	// Version is semantic version.
    26  	Version = "1.2.2"
    27  
    28  	// TokenTypeJwt is the JWT token type supported JWT tokens
    29  	// encoded and decoded by this library
    30  	TokenTypeJwt = "jwt"
    31  
    32  	// AlgorithmNkey is the algorithm supported by JWT tokens
    33  	// encoded and decoded by this library
    34  	AlgorithmNkey = "ed25519"
    35  )
    36  
    37  // Header is a JWT Jose Header
    38  type Header struct {
    39  	Type      string `json:"typ"`
    40  	Algorithm string `json:"alg"`
    41  }
    42  
    43  // Parses a header JWT token
    44  func parseHeaders(s string) (*Header, error) {
    45  	h, err := decodeString(s)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	header := Header{}
    50  	if err := json.Unmarshal(h, &header); err != nil {
    51  		return nil, err
    52  	}
    53  
    54  	if err := header.Valid(); err != nil {
    55  		return nil, err
    56  	}
    57  	return &header, nil
    58  }
    59  
    60  // Valid validates the Header. It returns nil if the Header is
    61  // a JWT header, and the algorithm used is the NKEY algorithm.
    62  func (h *Header) Valid() error {
    63  	if TokenTypeJwt != strings.ToLower(h.Type) {
    64  		return fmt.Errorf("not supported type %q", h.Type)
    65  	}
    66  
    67  	if alg := strings.ToLower(h.Algorithm); alg != AlgorithmNkey {
    68  		if alg == "ed25519-nkey" {
    69  			return fmt.Errorf("more recent jwt version")
    70  		}
    71  		return fmt.Errorf("unexpected %q algorithm", h.Algorithm)
    72  	}
    73  	return nil
    74  }